leetcode 刷題(2)--- 兩數相加
阿新 • • 發佈:2018-11-14
nullptr solution 原因 == 表示 node etc 數字 個數字 * temp = nullptr;
int sum = 0;
int carry = 0;
while (l1 != nullptr&&l2 != nullptr){
sum = (l1->val + l2->val) % 10 + carry; //當前位的和
carry = (l1->val + l2->val) / 10; //進位
if (result == nullptr){
temp = new ListNode(sum);
result = temp;
}
else {
temp->next = new ListNode(sum);
temp = temp->next;
}
l1 = l1->next;
l2 = l2->next;
}
while (l1 != nullptr){
temp->next = new ListNode(l1->val + carry);
temp = temp->next;
carry = 0;
}
while (l2 != nullptr){
temp->next = new ListNode(l2->val + carry);
temp = temp->next;
carry = 0;
}
if (carry == 1){
temp->next = new ListNode(1);
}
return result;
}
};
給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每個節點只存儲單個數字。將兩數相加返回一個新的鏈表。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
解法:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* result = nullptr;
ListNode
int sum = 0;
int carry = 0;
while (l1 != nullptr&&l2 != nullptr){
sum = (l1->val + l2->val) % 10 + carry; //當前位的和
carry = (l1->val + l2->val) / 10; //進位
if (result == nullptr){
temp = new ListNode(sum);
result = temp;
}
else
temp->next = new ListNode(sum);
temp = temp->next;
}
l1 = l1->next;
l2 = l2->next;
}
while (l1 != nullptr){
temp->next = new ListNode(l1->val + carry);
temp = temp->next;
carry = 0;
}
while
temp->next = new ListNode(l2->val + carry);
temp = temp->next;
carry = 0;
}
if (carry == 1){
temp->next = new ListNode(1);
}
return result;
}
};
leetcode 刷題(2)--- 兩數相加