Saturday, July 2, 2016

2. Add Two Numbers

Well, the code I wrote is long and tedious. It can be optimized for sure but it’s good enough for the interview because optimizing code is very volatile to errors. When I revisit this problem, I made mistake in line 40 - 43.

1:  /**  
2:   * Definition for singly-linked list.  
3:   * struct ListNode {  
4:   *   int val;  
5:   *   ListNode *next;  
6:   *   ListNode(int x) : val(x), next(NULL) {}  
7:   * };  
8:   */  
9:  class Solution {  
10:  public:  
11:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {  
12:      ListNode *dummy = new ListNode(-1);  
13:      ListNode *cur = dummy;  
14:      int carry = 0;  
15:      while (l1 && l2) {  
16:        int sum = l1->val + l2->val + carry;  
17:        carry = sum/10;  
18:        ListNode *node = new ListNode(sum%10);  
19:        cur->next = node;  
20:        cur = cur->next;  
21:        l1 = l1->next;  
22:        l2 = l2->next;  
23:      }  
24:      while (l1) {  
25:        int sum = l1->val + carry;  
26:        carry = sum/10;  
27:        ListNode *node = new ListNode(sum%10);  
28:        cur->next = node;  
29:        cur = cur->next;  
30:        l1 = l1->next;  
31:      }  
32:      while (l2) {  
33:        int sum = l2->val + carry;  
34:        carry = sum/10;  
35:        ListNode *node = new ListNode(sum%10);  
36:        cur->next = node;  
37:        cur = cur->next;  
38:        l2 = l2->next;  
39:      }  
40:      if (carry) {  
41:        ListNode *node = new ListNode(1);  
42:        cur->next = node;  
43:      }  
44:      cur = dummy->next;  
45:      delete dummy;  
46:      return cur;  
47:    }  
48:  };  

No comments:

Post a Comment