RT
string转 int
题目
https://leetcode.com/problems/string-to-integer-atoi/#/description
char 转 int 是 根据 ascii码, 数字从 48开始
思路是 先从字符串中 获取合法的 数字串
1.去除前后空格
2.判断第一个字符是否为 + - 来判断正负
3.最后计算的时候,还要注意边界 IntMax 是 2147483647 ,IntMin是 2147483648,越界的时候特殊处理就好
bool isNumber(char c)
{
if (c >= 48 && c <= 65)
return true;
return false;
}
//小写字母 97~122 ,大写之母是 65~90
public int MyAtoi(string str)
{
int ans = 0;
int numOffset = 48;
int temp = 1; //判断正负
List<int> nums = new List<int>();
//去除字符串前后的空格。。。
str = str.Trim();
if(str.Length > 0)
{
if (!isNumber(str[0]))
{
if (str[0] == '-' || str[0] == '+')
temp = str[0] == '-' ? -1 : 1;
else
return 0;
}
}
//先找出合法的数字串
for (int i = 0; i < str.Length; i++)
{
if (isNumber(str[i]))
{
int num = (int)(str[i] - numOffset);
nums.Add(num);
}
else if (i > 0)
break;
}
//计算数字串
int max = 2147483647;
int min = -2147483648;
for (int i = 0; i < nums.Count;i++ )
{
//要注意 边界。。
if(max - ans < nums[i])
{
ans = temp == -1? min:max;
break;
}
ans += nums[i] * (int)Math.Pow(10, nums.Count - 1 - i);
}
ans *= temp;
return ans;
}