Problem
Implement function atoi to convert a string to an integer.
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.
Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
Note
先用String.trim()
将str
前后的空格删去。
Method Returns : The trim() method of String class returns a new String object. The method returned value is a copy of the original String with leading and trailing spaces omitted.
然后设置正负值标记isNeg
。
循环str
的每个字符:
首先判断第一个字符,是否为'+'
或'-'
,以确定str
转化后的符号;
然后对中间进行转换:基于公式res = res * 10 + cur
,cur
为当前位的值。当然,要提前判断新的res
是否越界————res > (Integer.MAX_VALUE-cur)/10
,如果越界,则根据isNeg
返回整数最大值或整数最小值;
最后,排除str
中存在小数点'.'
的情况。
若str
后面的字符中没有小数点,那么循环走完之后,最后根据isNeg
返回res
或-res
。
Solution
public class Solution {
public int myAtoi(String str) {
str = str.trim();
boolean isNeg = false;
int res = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (i == 0 && (ch == '+' || ch == '-')) isNeg = ch == '+' ? false: true;
else if (ch >= '0' && ch <= '9') {
int cur = ch - '0';
if (res > (Integer.MAX_VALUE-cur)/10) return isNeg ? Integer.MIN_VALUE: Integer.MAX_VALUE;
else res = res*10+cur;
}
else return isNeg ? -res: res;
}
return isNeg? -res: res;
}
}