leetcode8

public class Solution {
    public int MyAtoi(string str) {
        int index = 0, sign = 1, total = 0;
            //1. Empty string
            if (str.Length == 0)
            {
                return 0;
            }
            //2. Remove Spaces
            while (str[index] == ' ' && index < str.Length)
            {
                index++;
            }

            //3. Handle signs
            if (str[index] == '+' || str[index] == '-')
            {
                sign = str[index] == '+' ? 1 : -1;
                index++;
            }

            //4. Convert number and avoid overflow
            while (index < str.Length)
            {
                int digit = str[index] - '0';
                if (digit < 0 || digit > 9) break;

                //check if total will be overflow after 10 times and add digit
                if (int.MaxValue / 10 < total || int.MaxValue / 10 == total && int.MaxValue % 10 < digit)
                {
                    return sign == 1 ? int.MaxValue : int.MinValue;
                }

                total = 10 * total + digit;
                index++;
            }
            return total * sign;
    }
}

https://leetcode.com/problems/string-to-integer-atoi/#/description

补充一个python的实现:

 1 class Solution:
 2     def myAtoi(self, string: str) -> int:
 3         string = string.strip()
 4         n = len(string)
 5         if n == 0:
 6             return 0
 7         sign = 0
 8         convertStr = '0'
 9         firstNum = False
10         for i in range(n):
11             c = ord(string[i]) - ord('0')
12             if not firstNum:
13                 if string[i] == '+' and sign == 0:
14                     sign = 1
15                 elif string[i] == '-' and sign == 0:
16                     sign = -1
17                 elif c >= 0 and c <= 9:
18                     firstNum = True
19                     if sign == 0:
20                         sign = 1
21                     convertStr += str(c)
22                 else:
23                     convertStr = '0'
24                     break
25             else:
26                 if c >= 0 and c <= 9:
27                     convertStr += str(c)
28                 else:
29                     break
30         r = int(convertStr) * sign
31         if r > 2 ** 31 - 1:
32             r = 2 ** 31 - 1
33         elif r < -(2 ** 31):
34             r = -(2 ** 31)
35         return r
原文地址:https://www.cnblogs.com/asenyang/p/6823759.html