String to Integer (atoi)

Description

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the > possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the > input requirements up front.

实现atoi功能

需要注意边界检查

Solution

 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
func myAtoi(str string) int {
    str = strings.TrimLeft(str, " ")

    if len(str) == 0 {
        return 0
    }

    r := 0
    sign := 1

    if str[0] == '-' {
        sign = -1
        str = str[1:]
    } else if str[0] == '+' {
        str = str[1:]
    }

    for i := 0; i < len(str); i++ {
        c := str[i]
        if c >= '0' && c <= '9' {
            r = r * 10 + (int(c - '0') * sign)

            if r <= math.MinInt32 {
                return math.MinInt32
            } else if r >= math.MaxInt32 {
                return math.MaxInt32
            }
        } else {
            break
        }
    }

    return r
}