-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-two-numbers.go
More file actions
50 lines (39 loc) · 875 Bytes
/
add-two-numbers.go
File metadata and controls
50 lines (39 loc) · 875 Bytes
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
42
43
44
45
46
47
48
49
50
// https://leetcode-cn.com/problems/add-two-numbers/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
dummyHead := &ListNode{Val: 0}
curr := dummyHead
p := l1
q := l2
carry := 0
for(p != nil || q != nil ) {
x := 0
if p != nil {
x = p.Val
}
y := 0
if q != nil {
y = q.Val
}
sum := x + y + carry
carry = sum / 10
curr.Next = &ListNode{Val: sum % 10}
curr = curr.Next
if p != nil {
p = p.Next
}
if q != nil {
q = q.Next
}
}
if carry > 0 {
curr.Next = &ListNode{Val: carry}
}
return dummyHead.Next
}