File tree Expand file tree Collapse file tree 3 files changed +62
-0
lines changed
Expand file tree Collapse file tree 3 files changed +62
-0
lines changed Original file line number Diff line number Diff line change @@ -9,5 +9,6 @@ leetcode for golang
99#### [ 5. longest palindromic substring] ( https://github.com/hitzzc/go-leetcode/tree/master/longest_palindromic_substring )
1010#### [ 6. zigzag conversion] ( https://github.com/hitzzc/go-leetcode/tree/master/zigzag_conversion )
1111#### [ 7. reverse integer] ( https://github.com/hitzzc/go-leetcode/tree/master/reverse_integer )
12+ #### [ 8. string to integer] ( https://github.com/hitzzc/go-leetcode/tree/master/string_to_integer )
1213
1314
Original file line number Diff line number Diff line change 1+ package string_to_integer
2+
3+ // just consider 32-bit, fucking leetcode.com's test cases
4+ const (
5+ MAX int32 = 1 << 31 - 1
6+ MIN int32 = - 1 * MAX - 1
7+ )
8+
9+ func myAtoi (str string ) int {
10+ if len (str ) == 0 {
11+ return 0
12+ }
13+ runes := []rune (str )
14+ var ret int32
15+ var neg bool
16+ i := 0
17+ for ; runes [i ] == rune (' ' ); i ++ {
18+ }
19+ if runes [i ] == rune ('-' ) || runes [i ] == rune ('+' ) {
20+ neg = runes [i ] == rune ('-' )
21+ i ++
22+ }
23+
24+ for ; i < len (runes ); i ++ {
25+ if val , ok := toInt (runes [i ]); ! ok {
26+ break
27+ } else {
28+ if neg {
29+ if - ret < (MIN + val )/ 10 {
30+ return int (MIN )
31+ }
32+ } else {
33+ if ret > (MAX - val )/ 10 {
34+ return int (MAX )
35+ }
36+ }
37+ ret = 10 * ret + val
38+ }
39+ }
40+ if neg {
41+ return int (- ret )
42+ }
43+ return int (ret )
44+ }
45+
46+ func toInt (r rune ) (int32 , bool ) {
47+ ret := int32 (r - rune ('0' ))
48+ if ret >= 0 && ret <= 9 {
49+ return ret , true
50+ }
51+ return 0 , false
52+ }
Original file line number Diff line number Diff line change 1+ package string_to_integer
2+
3+ import (
4+ "testing"
5+ )
6+
7+ func TestMyAtoi (t * testing ) {
8+
9+ }
You can’t perform that action at this time.
0 commit comments