[LeetCode] 2. Add Two Numbers (C++)
2208 ワード
タイトルの説明:
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:
解題の構想:チェーンテーブルを遍歴して、簡単な数学、1つの数で得た値の各位を一時的に保存して、1つは進位を一時的に保存します
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.
解題の構想:チェーンテーブルを遍歴して、簡単な数学、1つの数で得た値の各位を一時的に保存して、1つは進位を一時的に保存します
/**
* 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) {
if (!l1 || !l2)
return nullptr;
ListNode* resList = new ListNode(0);
ListNode* Now = resList;
int carry = 0;
int sum = 0;
ListNode* l = l1;
ListNode* r = l2;
while (l != nullptr && r != nullptr) {
sum = (l->val + r->val + carry) % 10;
carry = (l->val + r->val + carry) / 10;
ListNode* temp = new ListNode(sum);
Now->next = temp;
Now = temp;
l = l->next;
r = r->next;
}
while (l != nullptr) {
sum = (l->val + carry) % 10;
carry = (l->val + carry) / 10;
ListNode* temp = new ListNode(sum);
Now->next = temp;
Now = temp;
l = l->next;
}
while (r != nullptr) {
sum = (r->val + carry) % 10;
carry = (r->val + carry) / 10;
ListNode* temp = new ListNode(sum);
Now->next = temp;
Now = temp;
r = r->next;
}
if (carry == 0) {
Now -> next = nullptr;
} else {
Now->next = new ListNode(carry);
}
return resList->next;
}
};