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.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
spoilers alert... click to show requirements for atoi.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
题目意思是:
将一个字符串转换为整型
如果是空串则return 0;
除却前面的若干空格外,第一个字符可以是“+”,“-”以及数字,不能是字符,如果是字符则按return 0处理;
在数字串中如果有字符存在,则自动忽视后面的
比如+-12 则输出 0 算invalid
12a34 输出12 后面字母后的全部忽略
溢出的则输出INT的最大最小值,判断溢出可提前一位判断与Integer.MAX_VALUE/10的大小,防止溢出而导致的数据错误
Source
public static int atoi(String x) {
int flag = -1,pot = 0;
int num = 0;
if(x == null || x.length() == 0) return 0;
for(int i = 0; i < x.length(); i++)
if(x.charAt(i) == ' ') continue;
else if(x.charAt(i) == '-' || x.charAt(i) == '+' || (x.charAt(i) <= '9' && x.charAt(i) >= '0'))
{
flag = i;
break;
}
else break;
if(flag == -1) return 0;
if(x.charAt(flag) == '-')
{
pot = -1;
flag++;
}
else if(x.charAt(flag) == '+')
{
pot = 1;
flag++;
}
for(int i = flag; i < x.length(); i++)
{
if(x.charAt(i) <= '9' && x.charAt(i) >= '0') //charAt用于string中找i位置的元素
{
if(num < Integer.MAX_VALUE/10 ) num = num * 10 + x.charAt(i) - '0';
else if(num > Integer.MAX_VALUE/10)
{
if(pot == -1) return Integer.MIN_VALUE; //Integer.MIN_VALUE和MAX在java.lang下有时不会自动识别,前加java.lang即可识别
else return Integer.MAX_VALUE;
}
else if(num == Integer.MAX_VALUE/10)
{
if(pot != -1)
{
if(x.charAt(i) <= '7')
{
num = num * 10 + x.charAt(i) - '0';
break;
}
else if(x.charAt(i) > '7')
return Integer.MAX_VALUE;
}
else
{
if(x.charAt(i) < '8')
{
num = num * 10 + x.charAt(i) - '0';
break;
}
else if(x.charAt(i) >= '8')
return Integer.MIN_VALUE;
}
}
}
else break;
}
if(pot == -1) return -num;
else return num;
}