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.
**The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
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.
题目分析:自己实现一个atoi方法,众所周知atoi是C里面将字符串转换成整数的一个函数。这道题实现不难,就是要注意一下各种输入的处理,首先要判断输入字符是否为空或者为空字符串。开始是让抛出异常来处理的,没想到这题不让抛异常。。。只能返回数值。然后这题有个坑的地方就在于例如你输入123abc格式的,还是不能抛出异常,此时要返回123.这算个坑吧。然后就是对数值越界的情况的判断,踩完各种坑就可以了
public int myAtoi(String str) {
if (str == null || str.length() == 0)
return 0;
int index = 0;
while (str.charAt(index) == ' ' && index < str.length())
index++;
int sign = 1;
if (str.charAt(index) == '+') {
index++;
} else if (str.charAt(index) == '-') {
index++;
sign = -1;
}
int total = 0;
while (index < str.length()) {
int digit = str.charAt(index) - '0';
if (digit < 0 || digit > 9)
return sign * total;
if ((Integer.MAX_VALUE / 10 < total || Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit)) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
total = 10 * total + digit;
index++;
}
return total * sign;
}