You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
翻譯
有兩個(gè)代表兩組非負(fù)數(shù)字的鏈表。兩個(gè)鏈表按照逆序排序,并且每一個(gè)節(jié)點(diǎn)包含一位數(shù)字。把兩組數(shù)加起來,并且返回一個(gè)鏈表。
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
審題
1.鏈表
2.一位數(shù)字
3.返回鏈表
4.根據(jù)例子知道,
Output:7->0->8
其中
7=3+4;
0=4+6;
8=2+5+1(進(jìn)位);
隱藏問題
鏈表可能很長(zhǎng)很長(zhǎng)。。。所以不能總是遍歷
兩個(gè)鏈表可能不一樣的長(zhǎng)度,即有可能有些位不用做加法
我漏掉分析一個(gè),當(dāng)長(zhǎng)度一樣的兩個(gè)鏈表,最后一位相加進(jìn)位了,我們需要把進(jìn)位補(bǔ)到鏈表最后。。。
Input: (5) + (5)
Output: 0 -> 1
Mine: 0
解決方案
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
int carry = 0;
ListNode pointer = result;
while (l1 != null || l2 != null) {
//兩個(gè)有一個(gè)沒到頭,就繼續(xù)
if (l1 != null) {
carry += l1.val;
l1 = l1.next;
}
if (l2 != null) {
carry += l2.val;
l2 = l2.next;
}
pointer.next = new ListNode(carry%10);
carry /=10;
pointer = pointer.next;
}
if (carry > 0) {//記得處理最后的進(jìn)位。。。
pointer.next = new ListNode(carry);
}
return result.next;
}