问题描述:
Implement atoi to convert a string to an integer.
Hint: Carefullyconsider all possible input cases. If you want a challenge, please do not seebelow and ask yourself what are the possible input cases.
Notes: It isintended for this problem to be specified vaguely (ie, no given input specs).You are responsible to gather all the input requirements up front.
Update(2015-02-10):
The signature of the C++ functionhad been updated. If you still see your function signature accepts a const char * argument, please click the reload buttonto reset your code definition.
spoilers alert...click to show requirements for atoi.
Requirements for atoi:
The functionfirst discards as many whitespace characters as necessary until the firstnon-whitespace character is found. Then, starting from this character, takes anoptional initial plus or minus sign followed by as many numerical digits aspossible, and interprets them as a numerical value.
The stringcan 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 firstsequence of non-whitespace characters in str is not a valid integral number, orif no such sequence exists because either str is empty or it contains onlywhitespace characters, no conversion is performed.
If no validconversion could be performed, a zero value is returned. If the correct valueis out of the range of representable values, INT_MAX (2147483647) or INT_MIN(-2147483648) is returned.
代码:主要考虑多种情况即可:
参考C++的atoi: http://blog.csdn.net/woliuyunyicai/article/details/44101881
public class Solution { public int atoi(String str) { if(str == null || str.length() == 0) { return 0; } char[] str_arr = str.toCharArray(); boolean flag = true;//标志正数负数,正数为true long result = 0; int index = 0; final long MAX_INT = (long)(Math.pow(2, 31) -1);//在Java中可以使用Integer.MAX_VALUE替代 final long MIN_INT = (long)(-(Math.pow(2, 31))); int data_length = 0;//记录长度,防止Long也溢出的情况 //考虑前面字符为空格符的情况,如“ 010”,消除空格符可以使用String.trim() while(index < str.length() && str_arr[index] == ' ') { index++; } //首先判断第一个字符是正数还是负数“+,-”,进行标记 if(str_arr[index] == '+') { flag = true; ++index; } else if(str_arr[index] == '-') { flag = false; ++index; } //是否为'0'-'9'字符 while(index < str.length() && str_arr[index] <= '9' && str_arr[index] >= '0' && data_length++ <= 10)//data_length用来控制数字字符串过长 { result = result * 10 + (str_arr[index++] - '0'); } //判断是否int越界 result = flag ? result : -result; if (result > MAX_INT) { result = MAX_INT; } else if(result < MIN_INT){ result = MIN_INT; } return (int)result; } public static void main(String[] args) { //测试案例 // String str = " +004500"; // String str = " -0012a42"; // String str = "2147483648"; // String str = "-2147483648"; String str = "-9223372036854775809"; System.out.println(new Solution().atoi(str)); } }