[LeetCode] 8. String to Integer (atoi)

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm for myAtoi(string s) is as follows:

Whitespace: Ignore any leading whitespace (" ").
Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present.
Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.
Return the integer as the final result.

Example 1:
Input: s = "42"
Output: 42

Explanation:
The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^

Example 2:
Input: s = " -042"
Output: -42

Explanation:
Step 1: " -042" (leading whitespace is read and ignored)
^
Step 2: " -042" ('-' is read, so the result should be negative)
^
Step 3: " -042" ("042" is read in, leading zeros ignored in the result)
^

Example 3:
Input: s = "1337c0d3"
Output: 1337

Explanation:
Step 1: "1337c0d3" (no characters read because there is no leading whitespace)
^
Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+')
^
Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit)
^

Example 4:
Input: s = "0-1"
Output: 0

Explanation:
Step 1: "0-1" (no characters read because there is no leading whitespace)
^
Step 2: "0-1" (no characters read because there is neither a '-' nor '+')
^
Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit)
^

Example 5:
Input: s = "words and 987"
Output: 0

Explanation:
Reading stops at the first non-digit character 'w'.

Constraints:
0 <= s.length <= 200
s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.

字符串转换整数 (atoi)。

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。

函数 myAtoi(string s) 的算法如下:

读入字符串并丢弃无用的前导空格
检查下一个字符(假设还未到字符末尾)为正还是负号,读取该字符(如果有)。 确定最终结果是负数还是正数。 如果两者都不存在,则假定结果为正。
读入下一个字符,直到到达下一个非数字字符或到达输入的结尾。字符串的其余部分将被忽略。
将前面步骤读入的这些数字转换为整数(即,"123" -> 123, "0032" -> 32)。如果没有读入数字,则整数为 0 。必要时更改符号(从步骤 2 开始)。
如果整数数超过 32 位有符号整数范围 [−231, 231 − 1] ,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −231 的整数应该被固定为 −231 ,大于 231 − 1 的整数应该被固定为 231 − 1 。
返回整数作为最终结果。
注意:

本题中的空白字符只包括空格字符 ' ' 。
除前导空格或数字后的其余字符串外,请勿忽略 任何其他字符。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/string-to-integer-atoi
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

这题考察的是字符串转数字。需要注意的几个点是

  1. trim掉字符串中间,前后出现过的所有的空格。例子," 111 23 4 4 "需要处理成"1112344",跳过所有的空格。

  2. 先判断第一个char是不是一个正负号,若是负号记得最后乘以-1。

  3. 对于之后的字符串,判断每个char是不是介于0-9之间,若不是,立马退出循环。若是,就正常计算。因为是从左往右扫描,所以计算方式参见20行。

  4. 计算过程中如果有任何时候发现res大于Integer.MAX_VALUE也立马退出循环,并根据sign的正负返回Integer.MAX_VALUE或者Integer.MIN_VALUE

复杂度

时间O(n)
空间O(1)

代码

Java实现

class Solution {
    public int myAtoi(String str) {
        // corner case
        str = str.trim();
        if (str == null || str.length() == 0) {
            return 0;
        }

        // normal case
        char firstChar = str.charAt(0);
        int sign = 1;
        int start = 0;
        long res = 0;
        if (firstChar == '+') {
            sign = 1;
            start++;
        } else if (firstChar == '-') {
            sign = -1;
            start++;
        }
        for (int i = start; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return (int) res * sign;
            }
            res = res * 10 + str.charAt(i) - '0';
            if (sign == 1 && res > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            if (sign == -1 && res > Integer.MAX_VALUE) {
                return Integer.MIN_VALUE;
            }
        }
        return (int) res * sign;
    }
}

JavaScript实现

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
    // corner case
    str = str.trim();
    if (str == null || str.length == 0) {
        return 0;
    }

    // normal case
    let firstChar = str.charAt(0);
    let sign = 1;
    let i = 0;
    let res = 0;
    if (firstChar == '+') {
        sign = 1;
        i++;
    } else if (firstChar == '-') {
        sign = -1;
        i++;
    }
    while (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
        res = res * 10 + (str.charAt(i) - 0);
        if (res * sign >= 2147483647) {
            return 2147483647;
        } else if (res * sign <= -2147483648) {
            return -2147483648;
        }
        i++;
    }
    return res * sign;
};
posted @ 2019-10-13 01:06  CNoodle  阅读(454)  评论(0)    收藏  举报