持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第1天。
题目链接: leetcode.com/problems/st…
1. 题目介绍(字符串转整型)
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
【Translate】:实现myAtoi(string s)函数,它可以将字符串转换为32位符号整数(类似于C / C ++的atoi函数)
The algorithm for myAtoi(string s) is as follows:
【Translate】: myAtoi(string s) 算法如下:
- Read in and ignore any leading whitespace.
- Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
- Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
- Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
- If the integer is out of the 32-bit signed integer range [-2^31^, 2^31^ - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31^ should be clamped to -2^31^, and integers greater than 2^31^ - 1 should be clamped to 2^31^ - 1.
- Return the integer as the final result.
【Translate】:
- 阅读并忽略任何前缀的空白。
- 检查下一个字符(如果不在字符串的末尾)是否为'-'或'+'。如果是,读入这个字符。这将分别确定最终结果是负数还是正数。如果两者都不存在,则假定结果为正。
- 读入下一个字符,直到到达下一个非数字字符或输入结束。字符串的其余部分将被忽略。
- 将这些数字转换为整数(即。“123”-> 123,“0032”-> 32)。如果没有读取数字,则整数为0。根据需要改变符号(从步骤2开始)。
- 如果该整数在32位带符号整数范围[-2^31^,2^31^ - 1]之外,则夹住该整数,使其保持在该范围内。具体来说,小于-2^31^的整数要夹紧为-2^31^,大于2^31^ - 1的整数要夹紧为2^31^ - 1。
- 返回整数作为最终结果
Note:
- Only the space character ' ' is considered a whitespace character.
- Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
【Translate】:
- 只有空格字符
' '被视为空白字符。 - 不要忽略除前导空格或数字之后的字符串其余部分以外的任何字符。
测试用例:
约束:
2. 题解
2.1 顺序判断 -- O(n)
hi-malik的题解,目前Java Most Vote排名第二。
如上图所示,这就是题解的判断顺序,首先,我们先对空格进行处理,然后检查第一个非空格位是否有“+”或“-”符号标识,如果是“-”,则更改标志变量sign=-1。然后开始遍历后续字符是否为0-9的数字,同时进行越界判断。
public int myAtoi(String s) {
if (s.equals("")) {
return 0;
}
// helper variables
int res = 0, i = 0, sign = 1;
// get rid of whitespace
while (i < s.length() && s.charAt(i) == ' ') {
i++;
}
// check for sign
if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
// change if negative, iterate
if (s.charAt(i++) == '-') {
sign = -1;
}
}
// now iterate across digits if any
// should only be in range 0-9
while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
// check if we will go over the max
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && s.charAt(i) - '0' > 7)) {
if (sign == -1) {
return Integer.MIN_VALUE;
}
return Integer.MAX_VALUE;
}
// update res
res = res * 10 + (s.charAt(i++) - '0');
}
return sign * res;
}