Open fockspaces opened 1 year ago
先將 l1, l2 加完,接著把剩下的 list 跟 carry 加完即可
/**
* 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* head = new ListNode(); ListNode* cur = head;
int carry = 0;
while(l1 && l2) {
int sum = l1->val + l2->val + carry;
cur->next = new ListNode(sum % 10);
cur = cur->next; l1 = l1->next; l2 = l2->next;
carry = sum / 10;
}
ListNode* remain = l1 ? l1 : l2;
while(carry || remain) {
if(!remain) {cur->next = new ListNode(carry); break;}
int sum = remain->val + carry;
cur->next = new ListNode(sum % 10);
cur = cur->next; remain = remain->next;
carry = sum / 10;
}
return head->next;
}
};
簡化寫法,走到盡頭的視作 0 不貢獻值,判斷 l1, l2, carry 是否還有值,繼續運算
/**
* 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* head = new ListNode(); ListNode* cur = head;
int carry = 0;
while(l1 || l2 || carry) {
int a = l1 ? l1->val : 0;
int b = l2 ? l2->val : 0;
int sum = a + b + carry;
cur->next = new ListNode(sum % 10);
carry = sum / 10;
cur = cur->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return head->next;
}
};
https://leetcode.com/problems/add-two-numbers/description/