Skip to content

Commit cf2c24f

Browse files
committed
string-to-integer-atoi
1 parent 8054fd1 commit cf2c24f

File tree

2 files changed

+151
-0
lines changed

2 files changed

+151
-0
lines changed

string-to-integer-atoi/main.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package atoi
2+
3+
import (
4+
"strings"
5+
)
6+
7+
const intMax = 2147483647
8+
const intMin = -2147483648
9+
10+
func myAtoi(str string) int {
11+
prefix := 1
12+
str = strings.TrimSpace(str)
13+
l := len(str)
14+
if l == 0 {
15+
return 0
16+
}
17+
if str[0] == '-' || str[0] == '+' {
18+
if str[0] == '-' {
19+
prefix = -1
20+
}
21+
str = str[1:]
22+
l = len(str)
23+
if l < 1 {
24+
return 0
25+
}
26+
}
27+
num := 0
28+
i := 0
29+
for {
30+
c := byte(str[i])
31+
c = c - '0'
32+
if c > 9 {
33+
break
34+
}
35+
num = num*10 + int(c)
36+
i++
37+
if i > 10 && i < l {
38+
if prefix > 0 {
39+
return intMax
40+
}
41+
return intMin
42+
}
43+
if i >= l {
44+
break
45+
}
46+
}
47+
res := prefix * num
48+
if res >= intMax {
49+
return intMax
50+
}
51+
if res <= intMin {
52+
return intMin
53+
}
54+
return prefix * num
55+
}

string-to-integer-atoi/main_test.go

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package atoi
2+
3+
import (
4+
"fmt"
5+
"math"
6+
"strconv"
7+
"testing"
8+
)
9+
10+
func TestMyAtoi(t *testing.T) {
11+
testCases := []struct {
12+
Input string
13+
Output int
14+
}{
15+
{
16+
Input: "",
17+
Output: 0,
18+
},
19+
{
20+
Input: "-",
21+
Output: 0,
22+
},
23+
{
24+
Input: "+",
25+
Output: 0,
26+
},
27+
{
28+
Input: "0",
29+
Output: 0,
30+
},
31+
{
32+
Input: "123",
33+
Output: 123,
34+
},
35+
{
36+
Input: "-1",
37+
Output: -1,
38+
},
39+
{
40+
Input: "1",
41+
Output: 1,
42+
},
43+
{
44+
Input: "2147483648",
45+
Output: 2147483647,
46+
},
47+
{
48+
Input: strconv.Itoa(math.MinInt32),
49+
Output: -2147483648,
50+
},
51+
{
52+
Input: " 010",
53+
Output: 10,
54+
},
55+
{
56+
Input: "1a",
57+
Output: 1,
58+
},
59+
{
60+
Input: " -0012a42",
61+
Output: -12,
62+
},
63+
{
64+
Input: " -a1",
65+
Output: 0,
66+
},
67+
{
68+
Input: "9223372036854775809",
69+
Output: 2147483647,
70+
},
71+
{
72+
Input: " ",
73+
Output: 0,
74+
},
75+
{
76+
Input: " -1123u3761867",
77+
Output: -1123,
78+
},
79+
{
80+
Input: " -11919730356x",
81+
Output: -2147483648,
82+
},
83+
{
84+
Input: " -1010023630o4",
85+
Output: -1010023630,
86+
},
87+
}
88+
for _, test := range testCases {
89+
t.Run(fmt.Sprintf("input=%s output=%d", test.Input, test.Output), func(t *testing.T) {
90+
res := myAtoi(test.Input)
91+
if res != test.Output {
92+
t.Errorf("wanted %d, but got %d", test.Output, res)
93+
}
94+
})
95+
}
96+
}

0 commit comments

Comments
 (0)