1. 程式人生 > >LeetCode第二題:Add Two Numbers

LeetCode第二題:Add Two Numbers

ret lists exce sel onu plan each 們的 理解

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

給出兩個表示兩個非負整數的非空鏈表。整數以相反的順序存儲,它們的每個節點都包含一個數字。將兩個數字相加,並將其作為鏈接列表返回。

你可以假設這兩個數字不包含任何前導零,除了第0個數字本身。

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

題目本身不難,但是一定要記得最後的進位問題。下面貼下我的代碼,代碼量偏多,但是我認為比較好理解。

 1  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
2 ListNode root = new ListNode(0); 3 ListNode cur = root;//小技巧定義結果的上一個節點,返回時返回root.next 4 int temp = 0; //避免要先進行一次初值的計算 5 while (l1 != null || l2 != null) { 6 int n1 = 0; 7 int n2 = 0; 8 if (l1 != null) {//因為兩個數不一定一樣長,當一個數為空時, 9
n1 = l1.val; //用0計算即可,熟練的同學完全可以用三目運算符解決。 10 l1 = l1.next; 11 } 12 if (l2 != null) { 13 n2 = l2.val; 14 l2 = l2.next; 15 } 16 ListNode node = new ListNode((n1 + n2 + temp) % 10); 17 temp = (n1 + n2 + temp) / 10; 18 cur.next = node; 19 cur = node; 20 } 21 //這段代碼千萬不要忘記,如果最後有進位,需要添加節點。 22 //當然簡潔的代碼是在while循環中while (l1 != null || l2 != null||temp!=0) 23 //在循環中解決這個問題,我單獨列出來,希望大家牢記這一點,如果在面試中漏掉這種情況 24 //應該會在面試官那裏減分的。 25 if (temp != 0) { 26 cur.next = new ListNode(temp); 27 } 28 return root.next; 29 }

LeetCode第二題:Add Two Numbers