題目描述
給你兩個(gè) 非空 的鏈表,表示兩個(gè)非負(fù)的整數(shù)。它們每位數(shù)字都是按照 逆序 的方式存儲的,并且每個(gè)節(jié)點(diǎn)只能存儲 一位 數(shù)字。請你將兩個(gè)數(shù)相加,并以相同形式返回一個(gè)表示和的鏈表。你可以假設(shè)除了數(shù)字 0 之外,這兩個(gè)數(shù)都不會以 0 開頭。
例子
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807.
輸入:l1 = [0], l2 = [0]
輸出:[0]
輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]
題解:
按照題意,類比小學(xué)數(shù)學(xué)的兩位數(shù)加法,只需要將同位次的數(shù)字和“進(jìn)位”相加,就能得到最后結(jié)果。
設(shè)A數(shù)組為 A[m] = { $a_0 , a_1 , a_2 , \dots , a_{m-1} $ }, 相似地,B數(shù)組為B[n] = {$b_0 , b_1 , b_2 , \dots , b_{n-1} $}。文章來源:http://www.zghlxwxcb.cn/news/detail-662617.html
要得到C = A + B , 只需要 $$ c_i = a_i + b_i + t \qquad ,其中t為進(jìn)位 $$文章來源地址http://www.zghlxwxcb.cn/news/detail-662617.html
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *res = new ListNode();
ListNode *temp = res;
int t = 0;
while ( l1 || l2) { // l1和l2不一樣長,需要等到兩個(gè)數(shù)組都計(jì)算完畢才結(jié)束循環(huán)
if ( l1 ) {
t += l1->val; // t臨時(shí)變量加上l1數(shù)組當(dāng)前位次的值
l1 = l1->next; // l1 指向下一位,準(zhǔn)備下一個(gè)數(shù)字的計(jì)算
}
if ( l2) {
t += l2->val; // 同上
l2 = l2->next; // 同上
}
ListNode *newNode = new ListNode(t % 10); //調(diào)用構(gòu)造函數(shù)
temp->next = newNode;
temp = temp->next; // temp指針指向新節(jié)點(diǎn),保證temp指針指向的是末尾節(jié)點(diǎn)
t /= 10; // 這里的t 為 進(jìn)位 ,比如說 l1->val + l2->val = 13 ,那么插入的節(jié)點(diǎn)值為 13 % 10 == 3
//而進(jìn)位為 13 / 10 == 1
}
//當(dāng)計(jì)算完畢后,有可能還存在進(jìn)位,所以判斷t的值,如果不為0,就需要再插入到末尾節(jié)點(diǎn)。
if ( t > 0) {
ListNode *newNode = new ListNode(1);
temp->next = newNode;
}
//由于res是帶頭節(jié)點(diǎn)的單鏈表,要使得第一個(gè)節(jié)點(diǎn)就為元素,則返回下一個(gè)節(jié)點(diǎn)。
return res->next;
}
};
到了這里,關(guān)于兩數(shù)相加的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!