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.
題目分析:自己實(shí)現(xiàn)一個(gè)atoi方法娇掏,眾所周知atoi是C里面將字符串轉(zhuǎn)換成整數(shù)的一個(gè)函數(shù)娘荡。這道題實(shí)現(xiàn)不難喳挑,就是要注意一下各種輸入的處理蒲赂,首先要判斷輸入字符是否為空或者為空字符串乾胶。開(kāi)始是讓拋出異常來(lái)處理的善已,沒(méi)想到這題不讓拋異常鹏氧。飒筑。片吊。只能返回?cái)?shù)值。然后這題有個(gè)坑的地方就在于例如你輸入123abc格式的协屡,還是不能拋出異常俏脊,此時(shí)要返回123.這算個(gè)坑吧跌穗。然后就是對(duì)數(shù)值越界的情況的判斷不跟,踩完各種坑就可以了
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;
}