LeetCode 2. Add Two Numbers (两数相加)
题目标签:Linked List, Math
题目给了我们两个 Linked List, 各代表一个数字,不过顺序的反的。让我们把两个数字相加。
和普通的相加其实差不多,只不过变成了 Linked List, 还是要用到 / 和 %,具体看code。
Java Solution:
Runtime: 2ms, faster than 87%
Memory Usage: 44MB, less than 85%
完成日期:07/05/2019
关键点:利用 / 取得 carry;利用 % 取得 余数
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode cursor1 = l1; ListNode cursor2 = l2; ListNode cursor3 = dummyHead; int carry = 0; while(cursor1 != null || cursor2 != null) // go through both list { // if node exists, get the value, elsewise, default 0 int num1 = 0; int num2 = 0; if(cursor1 != null) num1 = cursor1.val; if(cursor2 != null) num2 = cursor2.val; int sum = num1 + num2 + carry; // update carry and sum carry = sum / 10; cursor3.next = new ListNode(sum % 10); cursor3 = cursor3.next; // move both list to next node if(cursor1 != null) cursor1 = cursor1.next; if(cursor2 != null) cursor2 = cursor2.next; } // at last, still need to check carry for last digit if(carry == 1) cursor3.next = new ListNode(1); return dummyHead.next; } }
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/