LeetCode - 8.String to Integer (atoi)

Implement atoi which converts a string to an integer.

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.

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.

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.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ' ' is considered as whitespace character.

  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^{31}, 2^{31} − 1]. If the numerical value is out of the range of representable values, INT_MAX or INT_MIN is returned.

    根据题意,Java限定在Integer中;

class Solution {
    public int myAtoi(String str) {
        if (str == null || str.trim().length() == 0){
            return 0;
        }
        str = str.trim();
        int flag = 1;
        int index = 0;
        int result = 0;
        if (str.charAt(index) == '+'){
            index++;
        }else if (str.charAt(index) == '-'){
            index++;
            flag = -1;
        }
        int bigInteger = Integer.MAX_VALUE/10;
        for (int i = index;i < str.length() && Character.isDigit(str.charAt(i));i++){
            int value = str.charAt(i) - '0';
            /*处理溢界*/
            if (result > bigInteger || (result == bigInteger && value > 7)){
                return flag == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            result = result * 10 + value;
        }
        return result * flag;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。