leetcode 8 String to Integer

2018-06-04 11:55:54 浏览数 (1)

代码语言:javascript复制
public class Solution {
    public int myAtoi(String str) {
        if (str.isEmpty()) return 0;
        int sign = 1, base = 0, i = 0, n = str.length();
        while (i < n && str.charAt(i) == ' ')   i;
        if (str.charAt(i) == ' ' || str.charAt(i) == '-') {
            sign = (str.charAt(i  ) == ' ') ? 1 : -1;
        }
        while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            base = 10 * base   (str.charAt(i  ) - '0');
        }
        return base * sign;
    }
}

0 人点赞