File tree 1 file changed +56
-0
lines changed
1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_solutions_golang
2
+
3
+ import (
4
+ "math"
5
+ "strings"
6
+ )
7
+
8
+ //https://leetcode.com/problems/string-to-integer-atoi/
9
+ func myAtoi (s string ) int {
10
+ s = strings .Trim (s , " " )
11
+ if len (s ) == 0 {
12
+ return 0
13
+ }
14
+ isNegative := false
15
+ index := - 1
16
+ isStarted := false
17
+ if ! (s [0 ] == '-' || (s [0 ] >= '0' && s [0 ] <= '9' ) || s [0 ] == '+' || s [0 ] == ' ' ) {
18
+ isStarted = true
19
+ }
20
+ for i := 0 ; i < len (s ) && ! isStarted ; i ++ {
21
+ if s [i ] == '-' {
22
+ isStarted = true
23
+ isNegative = true
24
+ index = i + 1
25
+ }
26
+ if s [i ] == '+' {
27
+ isStarted = true
28
+ index = i + 1
29
+ }
30
+ if s [i ] >= '0' && s [i ] <= '9' {
31
+ index = i
32
+ isStarted = true
33
+ }
34
+ }
35
+ if index < 0 {
36
+ return 0
37
+ }
38
+ result := int64 (0 )
39
+ for i := index ; i < len (s ); i ++ {
40
+ if s [i ] >= '0' && s [i ] <= '9' {
41
+ result = result * 10 + int64 (s [i ]- '0' )
42
+ if ! isNegative && result > math .MaxInt32 {
43
+ result = math .MaxInt32
44
+ }
45
+ if isNegative && result > math .MaxInt32 + 1 {
46
+ result = math .MaxInt32 + 1
47
+ }
48
+ } else {
49
+ break
50
+ }
51
+ }
52
+ if isNegative {
53
+ result = - result
54
+ }
55
+ return int (result )
56
+ }
You can’t perform that action at this time.
0 commit comments