Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9de5038

Browse files
author
Openset
committed
Add: add_two_numbers
1 parent c979212 commit 9de5038

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package add_two_numbers
2+
3+
import . "github.com/openset/leetcode/problems/000000"
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* type ListNode struct {
8+
* Val int
9+
* Next *ListNode
10+
* }
11+
*/
12+
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
13+
r := &ListNode{}
14+
t := r
15+
carry := 0
16+
for l1 != nil || l2 != nil || carry != 0 {
17+
val := carry
18+
if l1 != nil {
19+
val += l1.Val
20+
l1 = l1.Next
21+
}
22+
if l2 != nil {
23+
val += l2.Val
24+
l2 = l2.Next
25+
}
26+
t.Next = &ListNode{Val: val % 10}
27+
t = t.Next
28+
carry = val / 10
29+
}
30+
return r.Next
31+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,43 @@
11
package add_two_numbers
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
"github.com/openset/leetcode/problems/000000"
8+
)
9+
10+
type caseType struct {
11+
l1 []int
12+
l2 []int
13+
expected []int
14+
}
15+
16+
func TestAddTwoNumbers(t *testing.T) {
17+
tests := [...]caseType{
18+
{
19+
l1: []int{2, 4, 3},
20+
l2: []int{5, 6, 4},
21+
expected: []int{7, 0, 8},
22+
},
23+
{
24+
l1: []int{5},
25+
l2: []int{5},
26+
expected: []int{0, 1},
27+
},
28+
{
29+
l1: []int{5},
30+
l2: []int{5, 9, 9},
31+
expected: []int{0, 0, 0, 1},
32+
},
33+
}
34+
35+
for _, tc := range tests {
36+
l1 := base.SliceInt2ListNode(tc.l1)
37+
l2 := base.SliceInt2ListNode(tc.l2)
38+
output := base.ListNode2SliceInt(addTwoNumbers(l1, l2))
39+
if !reflect.DeepEqual(output, tc.expected) {
40+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.l1, tc.l2, output, tc.expected)
41+
}
42+
}
43+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /