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

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;
    }
}

Update 2018-10

class Solution {
    public int myAtoi(String str) {
        str = str.trim();
        if (str == null || str.length() == 0) return 0;
        boolean isPositive = true;
        int index = 0;
        if (str.charAt(0) == '-') {
            isPositive = false;
            index++;
        }
        if (str.charAt(0) == '+') {
            index++;
        }
        int sum = 0;
        while (index < str.length()) {
            char ch = str.charAt(index);
            if (ch < '0' || ch > '9') break;
            int digit = str.charAt(index)-'0';
            if ((Integer.MAX_VALUE-digit)/10 < sum) {
                return isPositive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            sum = sum*10+digit;
            index++;
        }
        return isPositive ? sum : -sum;
    }
}

linspiration
161 声望53 粉丝