[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 a whitespace character. - Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:
Input: str = "42" Output: 42
Example 2:
Input: str = " -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: str = "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: str = "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: str = "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.
Constraints:
0 <= s.length <= 200
s
consists of English letters (lower-case and upper-case), digits,' '
,'+'
,'-'
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实现
1 class Solution { 2 public int myAtoi(String str) { 3 // corner case 4 str = str.trim(); 5 if (str == null || str.length() == 0) { 6 return 0; 7 } 8 9 // normal case 10 char firstChar = str.charAt(0); 11 int sign = 1; 12 int start = 0; 13 long res = 0; 14 if (firstChar == '+') { 15 sign = 1; 16 start++; 17 } else if (firstChar == '-') { 18 sign = -1; 19 start++; 20 } 21 for (int i = start; i < str.length(); i++) { 22 if (!Character.isDigit(str.charAt(i))) { 23 return (int) res * sign; 24 } 25 res = res * 10 + str.charAt(i) - '0'; 26 if (sign == 1 && res > Integer.MAX_VALUE) { 27 return Integer.MAX_VALUE; 28 } 29 if (sign == -1 && res > Integer.MAX_VALUE) { 30 return Integer.MIN_VALUE; 31 } 32 } 33 return (int) res * sign; 34 } 35 }
JavaScript实现
1 /** 2 * @param {string} str 3 * @return {number} 4 */ 5 var myAtoi = function(str) { 6 // corner case 7 str = str.trim(); 8 if (str == null || str.length == 0) { 9 return 0; 10 } 11 12 // normal case 13 let firstChar = str.charAt(0); 14 let sign = 1; 15 let i = 0; 16 let res = 0; 17 if (firstChar == '+') { 18 sign = 1; 19 i++; 20 } else if (firstChar == '-') { 21 sign = -1; 22 i++; 23 } 24 while (str.charAt(i) >= '0' && str.charAt(i) <= '9') { 25 res = res * 10 + (str.charAt(i) - 0); 26 if (res * sign >= 2147483647) { 27 return 2147483647; 28 } else if (res * sign <= -2147483648) { 29 return -2147483648; 30 } 31 i++; 32 } 33 return res * sign; 34 };