String to Integer (atoi) LeetCode 解题报告

来源:互联网 发布:php有必要培训吗 编辑:程序博客网 时间:2024/06/10 03:01

题目

就是把输入的字符串转为整数,具体要求如下:
1、The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
译:(这个函数最开始丢弃空白字符知道第一个不空白字符的字符出现,然后从这个字符开始,接受一个可选的正号或负号,随后是尽可能多的数字,然后将它们解释为数值)。

2、The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
译:(这个字符串可以包含那些形成整数的额外字符,这些字符将被忽略,对这个函数的将不起作用)。[这句翻译我也有点迷糊,有更好的翻译希望留言讨论]

3、If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
译:(如果这个开始的为非空白字符不是合法的整数,或者是这个字符序列不存在因为它要么是空的要么是纯空白字符,不会发生转换)。

4、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.
译:(如果没有发生合法的转换,返回0. r如果这个正确值超出可表达的范围,返回整数的最大值(2147483647)或最小值(-2147483648))。

思路

题目细节较多,具体的要求在上面四点中,难度在于各种情况考虑周全。

代码

public int myAtoi(String str) {        int i = 0,res = 0,sign = 0,len = str.length()-1;        while(i <= len && str.charAt(i) == ' ')            i++;        if(i <= len && (str.charAt(i) == '-' || str.charAt(i) == '+')){            if(str.charAt(i) == '-'){                sign = -1;            }            i++;        }        while(i <= len && str.charAt(i) >= '0' && str.charAt(i) <= '9'){            if(res > Integer.MAX_VALUE / 10 || ((res == Integer.MAX_VALUE / 10)                     && str.charAt(i)-'0' > 7)){                if(sign == 1){                    return Integer.MAX_VALUE;                }else{                    return Integer.MIN_VALUE;                }            }            res = res*10 + str.charAt(i++)-'0';        }        return res*sign;    }
原创粉丝点击