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.
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.
将字符串转换为数字,需要注意的问题:字符串开始的空格,正负号,以及边界问题。public int atoi(String str) { int n = 0; int flag = 0; for(int i = 0; i < str.length(); i ++){ char ch = str.charAt(i); if(flag == 0 && ch == ' '){ continue; }else if(flag == 0 && ch == '-'){ flag = 1; }else if(flag == 0 && ch == '+'){ flag = 2; }else if(Character.isDigit(ch)){ if(i == 0){ flag = 3; } int rem = ch -'0'; if(n > 214748364){ if(flag == 1){ return -2147483648; }else { return 2147483647; } } if(n == 214748364){ if(flag == 1 && rem >= 8){ return -2147483648; }else if((flag == 2 || flag == 3) && rem > 7){ return 2147483647; } } n = 10 * n + rem; }else{ break; } } if(flag == 1){ n = -n; } return n; }
String to Integer (atoi),布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010378705/article/details/33328867