题目: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: [−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: "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.
题意:
字符串转换为整数并返回,转换过程过滤掉字符串有效字符(‘-’,‘+’,‘0至9’)前面的空格(Example 2),去除空格如果第一个字符不是有效字符,返回0(Example 4),否则返回转换后的数字(Example1), 忽略有效数字后面的无效字符(Example 3),如果转换后的数值超出有效范围( [−2^31, 2^31 − 1]),返回边界值(Example 5).
思路:
常规字符转换题目
- 找出字符串的第一个非空位置 nonzero。
- 判断是否位空字符串,为True 返回0, 为False,用i表示当前有效位,sign表示字符串表示的正负数,继续执行。
- 判断是否存在符号以及是否位有效数字。
- 结果范围数据类型使用longlong类型,接下来常规字符串转换数字。
- 添加符号,判断是否越界。
- 返回结果。
Code & C++
class Solution {
public:
int myAtoi(string str) {
auto nzero = str.find_first_not_of(' ');
if(nzero==string::npos) return 0;
int len = str.size(), i=nzero, sign=1;
if(str[i]=='-'){
sign = -1;
++i;
}else if(str[i]=='+'){
sign=1;
++i;
}else if(str[i] <'0' || str[i]>'9'){
return 0;
}
long long ans=0, imax,imin;
imax = (1<<31)-1;
imin = -imax-1;
while(i<len && str[i]>='0' && str[i]<='9'){
ans = ans*10 + (str[i]-'0');
if(ans>=imax+1)break;
++i;
}
ans*=sign;
if(ans>imax){
return imax;
}else if(ans<imin){
return imin;
}
return ans;
}
};
结果:
Runtime: 20 ms, faster than 97.74% of C++ online submissions for String to Integer (atoi).
Memory Usage: 14.6 MB, less than 100.00% of C++ online submissions for String to Integer (atoi).
Code & Python
相同的思路,使用python复现
class Solution:
def myAtoi(self, str: 'str') -> 'int':
if str.isspace() or str == '':return 0
str = str.lstrip();
ans, sign, i = 0, 1, 0
if str.isdigit():
ans = int(str)
elif str[0]=='-':
sign = -1
i+=1
elif str[0] == '+':
i+=1
elif not str[0].isnumeric():
return 0
if ans == 0:
for ch in str[i:]:
if ch.isnumeric():
ans = ans*10 + int(ch)
else:
break
INFMAX = (1<<31)-1
ans*=sign
if ans>INFMAX:
return INFMAX
elif ans<(-INFMAX-1):
return -INFMAX-1
return ans
结果:
Runtime: 56 ms, faster than 99.06% of Python3 online submissions for String to Integer (atoi).
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for String to Integer (atoi).
Status:Accepted