美文网首页
8. String to Integer (atoi)

8. String to Integer (atoi)

作者: Super_Alan | 来源:发表于2018-05-02 12:55 被阅读0次

    LeetCode Link

    将 string 转化为 int。规则如下:

    1. string 中允许 leading space
    2. 可以存在正负号
    3. string 中前一部分是可以转化为 int 的表达,后一部分可以是任意 characters, ignore and this is valid
    4. if invalid string, return 0
    5. if string value is greater than Integer.MAX or less than Integer.MIN,return Integer.MAX / Integer.MIN
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        int len = str.length();
        int index = 0;
        while (index < len && str.charAt(index) == ' ') {
            index++;
        }
        int sign = 1;
        if (index < len && (str.charAt(index) == '-' || str.charAt(index) == '+')) {
            sign = (str.charAt(index++) == '-') ? -1 : 1;
        }
        
        // invalid case
        if (index == len || str.charAt(index) > '9' || str.charAt(index) < '0') {
            return 0;
        }
        
        int res = 0;
        int maxValue = Integer.MAX_VALUE / 10;
        int lastDigitMax = (sign < 0) ? 8 : 7;
        while (index < len && str.charAt(index) >= '0' && str.charAt(index) <= '9') {
            int digit = (int)(str.charAt(index) - '0');            
            if ((res > maxValue) || (res == maxValue && digit > lastDigitMax)) {
                return (sign > 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            } 
            res = res * 10 + digit;
            index++;
        }
        
        return (sign < 0) ? -res : res;
    }
    

    相关文章

      网友评论

          本文标题:8. String to Integer (atoi)

          本文链接:https://www.haomeiwen.com/subject/yltcrftx.html