[LintCode/LeetCode] String to Integer

369 查看

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 + curcur为当前位的值。当然,要提前判断新的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;
    }
}