题目描述:
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.
题意:
- atoi函数是把字符串转行成integer类型的函数。
- 主要考虑许多情况:首先,去掉两边的空格,然后检查正负号,还有是循环读取每一个符合‘0’-‘9’的字符,还有越界的情况要注意
- 注意的是,最后答案要声明为double类型的,而不是int类型的
- 还要注意,while循环时,三个条件写一起,同时满足就进入循环体,如果只写i<s.length()的话,里面去判断是不是符合的,就会出现超时情况。
思路解析:
public class Solution {
public int atoi(String str) {
if(str==null || str.length()<1)
return 0;
String s= str.trim();
int i=0;
char flag = '+';
double res=0;
if(s.charAt(i)=='-'){
flag ='-';
i++;
}else if(s.charAt(i)=='+')
i++;
while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
res = s.charAt(i)-'0'+res*10;
i++;
}
if(flag=='-')
res= -res;
if(res>=Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if(res<=Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int)res;
}
}
代码: