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.
Link:https://leetcode.com/problems/string-to-integer-atoi/
思路:
1 如果出现字符 -> 则忽略
2 如果溢出overflow,返回最大值、最小值
3 符号位symbol
public static int MyAtoi(string str)
{
if (str == null || str.Length == 0)
return 0;
bool isNeg = false;
str = str.Trim();
char[] charArray = str.ToCharArray();
int curIndex = 0;
//获取整数符号
if (charArray[0] == '+')
{
isNeg = false;
curIndex++;
}
else if (charArray[0] == '-')
{
isNeg = true;
curIndex++;
}
else
isNeg = false;
//把字符串转换为整数
Int64 num = 0, absnum = 0;
char c;
while (curIndex < str.Length)
{
c = charArray[curIndex];
if (!Char.IsDigit(c))
break;
absnum = 10 * absnum + (c - '0');//c是字符串的asscii
if (isNeg)
num = -absnum;
else
num = absnum;
//判断是否溢出
if (num > Int32.MaxValue)
return Int32.MaxValue;
if (num < Int32.MinValue)
return Int32.MinValue;
curIndex++;
}
return (int)num;
}