问题链接:https://oj.leetcode.com/problems/string-to-integer-atoi/
问题描述:Implement atoi to convert a string to an integer.
API: public int atoi(String str)
分析:这连续几题都是数学题,这一题其实也不是很难。难的只是输入的不确定性,因为不能保证输入的合法。但根据spoiler(看链接)给出的提示和限定条件,只需要先用String.trim()去掉前后空格,判断第一位是否正负符号,然后不停往下走,遇到数字就算,遇到其他字符便停。overflow的检测和刚才Reverse Integer是一样的。
下面给出代码:
public int atoi(String str) {
str = str.trim();
int isNeg = 0;
if(str.length() == 0)
return 0;
if(str.charAt(0) == '+')
isNeg = 1;
else if(str.charAt(0) == '-')
isNeg = -1;
int res = 0;
int check = 0;
for(int i = isNeg == 0 ? 0 : 1; i < str.length(); i++){
char cur_bit = str.charAt(i);
if(cur_bit <= '9' && cur_bit >= '0'){
int cur_bit_num = (int)(cur_bit - '0');
res *= 10;
res += cur_bit_num * (isNeg == -1 ? -1 : 1);
if(res / 10 != check){
return isNeg == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
check = res;
}else{
break;
}
}
return res;
}