leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0445.cpp (1074B)
0 class Solution { 1 public: 2 pair<ListNode *, int> reverse(ListNode *root) { 3 ListNode *l = nullptr, *c = root; 4 int size = 0; 5 while (c) { 6 ListNode *n = c->next; 7 c->next = l; 8 l = c; 9 c = n; 10 size++; 11 } 12 return {l, size}; 13 } 14 15 ListNode *addTwoNumbers(ListNode *p1, ListNode *p2) { 16 auto [l1, s1] = reverse(p1); 17 auto [l2, s2] = reverse(p2); 18 19 if (s2 > s1) swap(l1, l2); 20 p1 = l1; 21 22 int carry = 0; 23 for (; l1 && l2; l1 = l1->next, l2 = l2->next) { 24 int sum = l1->val + l2->val + carry; 25 l1->val = sum % 10; 26 carry = sum / 10; 27 } 28 29 if (l1) { 30 while (true) { 31 int sum = l1->val + carry; 32 l1->val = sum % 10; 33 carry = sum / 10; 34 if (!l1->next) break; 35 l1 = l1->next; 36 } 37 } 38 39 if (!carry) return reverse(p1).first; 40 return new ListNode(carry, reverse(p1).first); 41 } 42 };