題目要求
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
LeetCode 2在線測試
問題描述
給定兩個非空單向鏈表代表兩個非負整數。整數中每一位的數字都逆序存儲在鏈表節點中,求出
這兩個非負整數的和並將結果中的數字以相同的逆序方式存儲在一個單項鏈表中。可以不考慮
數字前面的0。
例如:輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出 :7 -> 0 -> 8
思路分析
用LinkList代表整數中每一個數字,模擬加法進位的方式進行求和計算。例如:2 -> 4 -> 3
和5 -> 6 -> 4,先計算個位數 2和5的和為7, 十位數 4和6的和為10,逢十進一,則該位的數字
為0,產生一位進位1到百位參與百位的數字求和。那么百位的結果:3 + 4 + 1(這個1就是剛剛十位
相加產生的進位),百位計算結果為8,所以最終返回結果 7 -> 0 -> 8
代碼驗證
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* pRoot = NULL;
do {
if (l1 == NULL) {
pRoot = l2;
break;
}
if (l2 == NULL) {
pRoot = l1;
break;
}
int sum = l1->val + l2->val;
int digit = sum % 10;
int carry = sum / 10;
pRoot = new ListNode(digit);
ListNode* pTail = pRoot;
l1 = l1->next;
l2 = l2->next;
while (l1 != NULL || l2 != NULL) {
int sum = ((l1 != NULL) ? l1->val : 0) + ((l2 != NULL) ? l2->val : 0) + carry;
int digit = sum % 10;
carry = sum / 10;
ListNode* pNew = new ListNode(digit);
pTail->next = pNew;
pTail = pNew;
l1 = l1 != NULL ? l1->next : NULL;
l2 = l2 != NULL ? l2->next : NULL;
}
if (carry == 1) {
ListNode* pNew = new ListNode(carry);
pTail->next = pNew;
}
} while (false);
return pRoot;
}
};
總結注意
- 需要考慮大數情況,所以不能直接用int保存每個LinkList對應的值
- 考慮 [5] [5] -> [0, 1] 這種單獨進位的情況
原創聲明
作者:hgli_00
鏈接:http://www.cnblogs.com/lihuagang/p/leetcode_2.html
來源:博客園
著作權歸作者所有,轉載請聯系作者獲得授權。