Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Output: 7 -> 0 -> 8
class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { // Start typing your C/C++ solution below // DO NOT write int main() function int carry = 0; ListNode *root = l1 ? l1 : l2, *node = root; while (l1 && l2) { int val = l1->val + l2->val + carry; if (val > 9) { val %= 10; carry = 1; } else { carry = 0; } node = l1; node->val = val; l1 = l1->next; l2 = l2->next; } ListNode *next = l1 ? l1 : l2; if (next) { node->next = next; node = node->next; while (carry != 0) { int val = node->val + carry; if (val > 9) { node->val = val % 10; carry = 1; if (!node->next) { node->next = new ListNode(1); carry = 0; } else { node = node->next; } } else { node->val = val; carry = 0; } } } if (carry != 0) { node->next = new ListNode(1); } return root; } };
No comments:
Post a Comment