Skip to content

Commit 8175c97

Browse files
committed
string to integer
1 parent 2a48119 commit 8175c97

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

8.string-to-integer-atoi.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package leetcode
2+
3+
import (
4+
"strings"
5+
)
6+
7+
/*
8+
* @lc app=leetcode id=8 lang=golang
9+
*
10+
* [8] String to Integer (atoi)
11+
*/
12+
13+
// @lc code=start
14+
func myAtoi(s string) int {
15+
s = strings.TrimSpace(s)
16+
if len(s) == 0 {
17+
return 0
18+
}
19+
var sign int
20+
if s[0] == '-' {
21+
sign = -1
22+
s = s[1:]
23+
} else if s[0] == '+' {
24+
sign = 1
25+
s = s[1:]
26+
} else {
27+
sign = 1
28+
}
29+
var res int
30+
for i := 0; i < len(s); i++ {
31+
if s[i] < '0' || s[i] > '9' {
32+
break
33+
}
34+
res = res*10 + int(s[i]-'0')
35+
if res > 2147483647 {
36+
break
37+
}
38+
}
39+
res = res * sign
40+
if res > 2147483647 {
41+
return 2147483647
42+
}
43+
if res < -2147483648 {
44+
return -2147483648
45+
}
46+
return res
47+
}
48+
49+
// @lc code=end

0 commit comments

Comments
 (0)