LeetCode(11) atoi

Time:2022-8-5

topic:

Please implement an atoi function that converts strings to integers.

First, the function discards useless leading space characters as needed until the first non-space character is found. The following conversion rules are as follows:

If the first non-blank character is a positive or negative sign, combine that sign with as many consecutive numeric characters as possible to form a signed integer.
If the first non-blank character is a digit, it is directly combined with subsequent consecutive digit characters to form an integer.
The string may also have extra characters after the valid integer part, then these characters can be ignored, they should not affect the function.
Note: If the first non-whitespace character in the string is not a valid integer character, if the string is empty, or if the string contains only whitespace characters, your function does not need to convert, i.e. it cannot convert effectively.

In any case, if the function cannot perform a valid conversion, return 0.

hint:

Whitespace characters in this question only include the space character ' ' .
Assuming that our environment can only store signed integers of size 32 bits, then its value range is [−231, 231 − 1]. If the value is outside this range, return INT_MAX (231 − 1) or INT_MIN (−231).

Ideas:

There is nothing special about the idea of ​​​​this question, that is, first remove the leading and trailing spaces, then perform a symbol check on the first bit, and finally convert the number to an integer.

func myAtoi(s string) int {
    //1. If there is a space to remove the beginning of the string
    s = strings.TrimSpace(s)
    sig := 1
    ans := 0
    if len(s)==0{return 0}
    //2. Read the first character to determine whether it is a symbol or a number
    switch  {
    case s[0]=='-':
        sig = -1
    case s[0]=='+':
        sig = 1
    case '0'<=s[0]&&s[0]<='9':
        ans = int(s[0]-'0')
    default:
        return 0
    }
    //3. Read the remaining numbers
    //4. Returns when the first non-number is read or the reading is completed
    for i:=1;i<len(s);i++{
        if !('0'<=s[i]&&s[i]<='9'){
            break
        }
        if ans > math.MaxInt32/10 || (ans == math.MaxInt32 / 10 && sig*int(s[i]-'0') > 7) {return math.MaxInt32}
        if ans < math.MinInt32/10 || (ans == math.MinInt32 / 10 && sig*int(s[i]-'0') < -8){return math.MinInt32}
        ans = ans * 10+sig*int(s[i]-'0')
    }
    return ans
}

LeetCode(11)  atoi