leetcode-2:Add Two Numbers 兩數相加
阿新 • • 發佈:2018-12-14
題目:
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
給出兩個 非空 的連結串列用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式儲存的,並且它們的每個節點只能儲存 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的連結串列來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807
思路:兩個連結串列逐一 相加,carry用來儲存進位,將相加之和儲存到新建節點中,直到兩個連結串列都為空。 如果一個為空另一個不為空我們可以令為空的 值為0,一直處理。
/** * 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 *res = new ListNode(-1); ListNode *cur = res; int carry =0,n1=0,n2=0; while(l1 || l2) { if(l1==NULL) n1=0; else n1=l1->val; if(l2==NULL) n2=0; else n2=l2->val; int sum = n1 + n2 +carry; carry = sum/10; cur->next = new ListNode(sum%10); cur = cur->next; if(l1) l1=l1->next; if(l2) l2=l2->next; } if(carry) cur->next = new ListNode(carry); return res->next; } };
注意坑:一定要 判斷連結串列是否為空
延伸:如果 兩個連結串列值是 順序的,求他們 的和,可以先對他們進行逆序。在用這種方法操作。