-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathatoi.go
More file actions
36 lines (32 loc) · 653 Bytes
/
atoi.go
File metadata and controls
36 lines (32 loc) · 653 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main
import "fmt"
func main() {
fmt.Println(Atoi("12345"))
fmt.Println(Atoi("0000000012345"))
fmt.Println(Atoi("012 345"))
fmt.Println(Atoi("Hello World!"))
fmt.Println(Atoi("+1234"))
fmt.Println(Atoi("-1234"))
fmt.Println(Atoi("++1234"))
fmt.Println(Atoi("--1234"))
}
func Atoi(s string) int {
var n int
sliceS := []rune(s)
first := true
for i := 0; i < len(sliceS); i++ {
if (sliceS[0] == '-' || sliceS[0] == '+') && first {
first = false
continue
}
if sliceS[i] > '9' || sliceS[i] < '0' {
return 0
}
n = n*10 + int(sliceS[i]-'0')
}
if sliceS[0] == '-' {
return -n
}
return n
}
// quest 3 / checkpoint