LeetCode 2 两数相加
https://leetcode-cn.com/problems/add-two-numbers/
一道相对简单的题目,模拟两个数的加法即可。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int sum = 0, carry = 0;
ListNode dummy(0);
ListNode *tail = &dummy;
while (l1 != nullptr && l2 != nullptr) {
sum = l1->val + l2->val + carry;
carry = sum / 10;
sum = sum % 10;
tail->next = new ListNode(sum);
tail = tail->next;
l1 = l1->next;
l2 = l2->next;
}
ListNode *left = l1 == nullptr ? l2 : l1;
while (left != nullptr) {
sum = left->val + carry;
carry = sum / 10;
sum = sum % 10;
tail->next = new ListNode(sum);
tail = tail->next;
left = left->next;
}
if (carry > 0) tail->next = new ListNode(carry);
return dummy.next;
}
};