Tuesday, August 8, 2017

8. String to Integer (atoi)

Version #2 不用Long [TODO]
懒得想了


Version #1 纯自己发明的粗糙的方法 用Long放结果然后check溢出
遇到非digit位直接返回之前的计算结果
e.g. 123a123 return 123

大于Integer.MAX_VALUE 直接返回Integer.MAX_VALUE
小于Integer.MIN_VALUE  直接返回Integer.MIN_VALUE

像+-123这种直接返回0


所以,有必要解释一下题目的要求:

1. 首先需要丢弃字符串前面的空格;

2. 然后可能有正负号(注意只取一个,如果有多个正负号,那么说这个字符串是无法转换的,返回0。比如测试用例里就有个“+-2”);

3. 字符串可以包含0~9以外的字符,如果遇到非数字字符,那么只取该字符之前的部分,如“-00123a66”返回为“-123”;

4. 如果超出int的范围,返回边界值(2147483647或-2147483648)。


 77.46 % 



public class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) return 0;
        char[] chars = str.trim().toCharArray();
        Long result = 0L;
        boolean negative = false;
        for (int i = 0; i < chars.length; i++) {
            if (result > Integer.MAX_VALUE) break;
     
            if(chars[i] == '-') {
                if (i == 0) negative = true;
                else return 0;
            }
            else if (chars[i] == '+') {
                if (i == 0) negative = false;
                else return 0;
            }
            else {
                //check if it is a digit
                int digit = chars[i] - '0';
                if (digit < 0 || digit > 9) break;
                result = result * 10 + digit;
            }
        }
        if (negative) {
            result = -1L * result;
            if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        }
        if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        return result.intValue();
    }
}


No comments:

Post a Comment