public class Solution {
public int MyAtoi(string str) {
int index = , sign = , total = ;
//1. Empty string
if (str.Length == )
{
return ;
}
//2. Remove Spaces
while (str[index] == ' ' && index < str.Length)
{
index++;
} //3. Handle signs
if (str[index] == '+' || str[index] == '-')
{
sign = str[index] == '+' ? : -;
index++;
} //4. Convert number and avoid overflow
while (index < str.Length)
{
int digit = str[index] - '';
if (digit < || digit > ) break; //check if total will be overflow after 10 times and add digit
if (int.MaxValue / < total || int.MaxValue / == total && int.MaxValue % < digit)
{
return sign == ? int.MaxValue : int.MinValue;
} total = * total + digit;
index++;
}
return total * sign;
}
}

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

补充一个python的实现:

 class Solution:
def myAtoi(self, string: str) -> int:
string = string.strip()
n = len(string)
if n == :
return
sign =
convertStr = ''
firstNum = False
for i in range(n):
c = ord(string[i]) - ord('')
if not firstNum:
if string[i] == '+' and sign == :
sign =
elif string[i] == '-' and sign == :
sign = -
elif c >= and c <= :
firstNum = True
if sign == :
sign =
convertStr += str(c)
else:
convertStr = ''
break
else:
if c >= and c <= :
convertStr += str(c)
else:
break
r = int(convertStr) * sign
if r > ** - :
r = ** -
elif r < -( ** ):
r = -( ** )
return r
05-28 21:02