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 fc0d9ca

Browse files
author
Shuo
authored
Merge pull request #318 from openset/develop
Add: Add to Array-Form of Integer
2 parents f09ac6e + 63e2b54 commit fc0d9ca

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package add_to_array_form_of_integer
2+
3+
func addToArrayForm(A []int, K int) []int {
4+
ans, carry, l := make([]int, 0), 0, len(A)-1
5+
for carry > 0 || K > 0 || l >= 0 {
6+
x := K%10 + carry
7+
if l >= 0 {
8+
x, l = x+A[l], l-1
9+
}
10+
carry, K = x/10, K/10
11+
ans = append([]int{x % 10}, ans...)
12+
}
13+
return ans
14+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package add_to_array_form_of_integer
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input []int
10+
k int
11+
expected []int
12+
}
13+
14+
func TestAddToArrayForm(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
input: []int{1, 2, 0, 0},
18+
k: 34,
19+
expected: []int{1, 2, 3, 4},
20+
},
21+
{
22+
input: []int{2, 1, 5},
23+
k: 806,
24+
expected: []int{1, 0, 2, 1},
25+
},
26+
{
27+
input: []int{9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
28+
k: 1,
29+
expected: []int{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
30+
},
31+
}
32+
for _, tc := range tests {
33+
output := addToArrayForm(tc.input, tc.k)
34+
if !reflect.DeepEqual(output, tc.expected) {
35+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
36+
}
37+
}
38+
}

0 commit comments

Comments
(0)

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