8. String to Integer (atoi) 字符串转成整数

[抄题]:

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 (−231) is returned.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

根本不知道应该怎么处理越界啊:

先设置一个bound变量,-2147483648/10。当前num > bound || num == bond & digit > 7都不行

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

写整齐点,要考虑到的问题:空格(用trim)、符号(用标记变量)、越界

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 注意要把string转成字符才能操作
  2. 字符不是统一处理的 在符号处理和越界处理之后,都要再分别进行i++

[二刷]:

  1. 整数的范围是 ‘0’  <= c <= '9',必须有等号

[三刷]:

  1.  num的进位方式是 num = num * 10 + digit digit是最后一位数,不用新相乘

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

 digit是最后一位数,不用新相乘

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

class Solution {
    public int myAtoi(String str) {
        //handle space
        str = str.trim();
        int i = 0;
        char[] c = str.toCharArray();
        
        //signs
        int sign = 1;
        if (i < c.length && (c[i] == '+' || c[i] == '-')) {
            if (c[i] == '-') sign = -1;
            i++;
        }
        
        //out of bound in two ways
        int bound = Integer.MAX_VALUE / 10;
        int num = 0;
        while (i < c.length && (c[i] >= '0' && c[i] <= '9')){
            int digit = c[i] - '0';
            
            //out of bound
            if (num > bound || (num == bound && digit > 7)) {
                //depend on sign
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            num = digit + num * 10;
            i++;
        }

        return num * sign;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/9383582.html