[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 (2的31次幂 − 1) or INT_MIN (−2的31次幂) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−2的31次幂) is returned.

 题目分析

本题要求跳过给定字符串前面的所有的空格,如果前面是字母,则直接跳出循环,如果前面是正负号,则结果也是整数或者负数,如果在遍历数字的过程中遇到了字母,则直接跳出,将已经遍历过的数字返回,注意:题目的最后一条如果结果超过了int的最大值,则返回int的最大值,遇到这种最大值求解的问题要考虑好返回结果跟给定字符串拼接成的数的关系,再决定是否需要把最大值完全计算出来

  具体解法

字符串中的数字跟返回值的唯一关系就是如果超过int的最大值/最小值,那么就直接返回int的最大值/最小值,所以我们不需要完全输出字符串拼接成的数值,而是判断如果遍历的过程中字符组成的数字的大小超过了int的最大值/最小值,就直接返回int的最大值或者最小值,理解了这点就很简单了,设置一个数total用来记录当前字符串拆分出来的数字大小,每次遍历到数字都判断如果integer.maxValue/10 < total 说明在接下来的integer.maxValue < total*10, 而接下来的total会*10加上当前遍历出来的数字,所以会超过maxValue,直接根据正负号返回integermaxValue或者minValue,如果maxValue/10 == total,那么就要比对是maxValue的最后一位大还是即将加给total的当前为大,如果超过了,根据正负号返回结果,如果没有超过maxValue,那么就直接返回total, 注意:排除非数字字符的时候要注意全空格的情况


public class Solution {

    public int myAtoi(String str) {

        if (str == null || str.length() == 0) {

            return 0;
        }
        // 在这里进行第一位的判断
        char[] chars = str.toCharArray();
        int i = 0;
        // 用来进行当前值的运算
        int total = 0;
        // 在这里记录是否是正数
        int isPositive = 1;
        for (; i < chars.length; i++) {

            // 如果开头是空格,则继续向下
            if (chars[i] == ' ') {

                continue;
            }

            if (chars[i] == '+' || chars[i] == '-'){

                // 在这里判断是否是正数
                isPositive = chars[i] != '-' ?  1 : -1;
                i++;
                break;
            }

            // 如果第一个不是空格的位
            if (chars[i] != '+' && chars[i] != '-' && !(chars[i] >= '0' && chars[i] <= '9')) {

                return 0;
            }

            // 如果开头是数字,直接返回
            break;
        }

        // 这里判断如果都是空格的情况
        if(i == chars.length){

            return 0;
        }

        for (; i < chars.length; i++) {

            if (chars[i] < '0' || chars[i] > '9') {

                break;
            }

            // 如果maxValue/10<total,说明maxValue<total*10,超过范围
            // 如果maxValue/10 == total,还需要判断接下来要加上的chars[i] - '0'和maxValue的最后位谁比较大
            if((Integer.MAX_VALUE / 10 < total) || (Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < chars[i] - '0') ){

                return isPositive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            total = total * 10 + (chars[i] - '0');
        }

        return total * isPositive;
    }

    public static void main(String[] args) {

        Solution s = new Solution();
        if((true) || (false && false)){
            System.out.println("xixixi");
        }
        System.out.println(s.myAtoi("-91283472332"));
    }
}

猜你喜欢

转载自blog.csdn.net/zhttly/article/details/82784095