[InterviewBit] Add Two Numbers as Lists

Add Two Numbers as Lists

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
ListNode* dummy = new ListNode(-1);
ListNode* runner = dummy;
int carry = 0;
while(A and B) {
int sum = A->val + B->val + carry;
carry = sum / 10;
runner->next = new ListNode(sum%10);
runner = runner->next;
A = A->next;
B = B->next;
}

while(A) {
int sum = A->val + carry;
carry = sum / 10;
runner->next = new ListNode(sum%10);
runner = runner->next;
A = A->next;
}

while(B) {
int sum = B->val + carry;
carry = sum / 10;
runner->next = new ListNode(sum%10);
runner = runner->next;
B = B->next;
}

if(carry) runner->next = new ListNode(carry);

return dummy->next;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/14/PS/interviewbit/add-two-numbers-as-lists/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.