Skip to content

Commit c88c1fc

Browse files
author
Openset
committed
Add: plus_one
1 parent 05bf393 commit c88c1fc

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

problems/plus-one/plus_one.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,16 @@
11
package plus_one
2+
3+
func plusOne(digits []int) []int {
4+
l := len(digits)
5+
for i := l - 1; i >= 0; i-- {
6+
if digits[i] < 9 {
7+
digits[i]++
8+
return digits
9+
}
10+
digits[i] = 0
11+
}
12+
if digits[0] == 0 {
13+
digits = append([]int{1}, digits...)
14+
}
15+
return digits
16+
}

problems/plus-one/plus_one_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
11
package plus_one
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input []int
10+
expected []int
11+
}
12+
13+
func TestPlusOne(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: []int{1, 2, 3},
17+
expected: []int{1, 2, 4},
18+
},
19+
{
20+
input: []int{4, 3, 2, 1},
21+
expected: []int{4, 3, 2, 2},
22+
},
23+
{
24+
input: []int{1, 2, 9, 9},
25+
expected: []int{1, 3, 0, 0},
26+
},
27+
{
28+
input: []int{9, 9},
29+
expected: []int{1, 0, 0},
30+
},
31+
}
32+
33+
for _, tc := range tests {
34+
output := plusOne(tc.input)
35+
if !reflect.DeepEqual(output, tc.expected) {
36+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)