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è)鏈表(代表兩個(gè)非負(fù)數(shù)),數(shù)字的各位以倒序存儲(chǔ)什湘,將兩個(gè)代表數(shù)字的鏈表想加獲得一個(gè)新的鏈表(代表兩數(shù)之和)业踏。
如(2->4->3)(342) + (5->6->4)(465) = (7->0->8)(807)
設(shè)兩個(gè)進(jìn)行加法運(yùn)算的鏈表分別為l1,l2, sum鏈表為l3.
若以l[i] 表示鏈表各個(gè)節(jié)點(diǎn)的值涧卵,nCarryBit[i]表示l[i]位相加產(chǎn)生的進(jìn)位符
則有以下結(jié)論:
l3[i] = (l1[i] + l2[i] + nCarryBit[i-1]) % 10
nCarryBit[i] = (l1[i] + l2[i] + nCarryBit[i-1]) / 10
且nCarryBit[0] = 0;
Solution
/**
* 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) {
int v1,v2;
int nCarryBit = 0;
ListNode* Prehead = new ListNode(0);
ListNode* l3 = Prehead;
while(l1 || l2 ||nCarryBit)
{
v1 = 0, v2 = 0;
if(l1)
{
v1 = l1->val;
l1 = l1->next;
}
if(l2)
{
v2 = l2->val;
l2 = l2->next;
}
int sum = v1 + v2 +nCarryBit;
nCarryBit = sum/10;
l3->next = new ListNode(sum%10);
l3 = l3->next;
}
return Prehead->next;
}
};