description
Atoi you to implement a function, it can convert a string to an integer.
First, the function will begin with a space character discard useless if necessary, until the find to the first non-space character so far.
When we find the first non-space character is a positive or negative number, the combination of the symbols as much as possible with consecutive numbers up later, as the sign of integer; if the first non-space character is figures, which directly after the continuous numeric characters are combined to form an integer.
In addition to the string after a valid integer part may also exist extra characters, these characters can be ignored, they should not affect a function.
Note: if the character string in the first non-space character is not a valid integer character string is empty or contains only white space character string, then you will not need to be a function of conversion.
In any case, if the function can not effectively convert, 0 is returned.
Description:
We assume that the size of the environment can store 32-bit signed integer, then the value range of [-231 231--1]. If the value exceeds this range, return INT_MAX (231 - 1) or INT_MIN (-231)
Examples of
ideas
- python: numeric characters get int ©
- c ++: characters get a digital c-'0 '
answers - python
方法1 正则表达式
def myAtoi(self, s: str) -> int:
return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)
方法2:
class Solution:
def myAtoi(self, s: str) -> int:
INT_MAX = 2**31-1
INT_MIN = -(2**31)
flag = 1
num=0
for i in range(len(s)):
if not s[i].isspace():
if s[i]=='-' or s[i]=='+':
if s[i]=='-':
flag = -1
#为'+'时,符号不变
i = i+1
while i<len(s) and s[i].isdigit():
num = num*10+int(s[i])
if num*flag < INT_MIN: return INT_MIN
if num*flag > INT_MAX: return INT_MAX
i = i+1
break
return num*flag
- c++
class Solution {
public:
int myAtoi(string s) {
long num=0;
int flag = 1;
for (int i=0; i<s.size(); i++)
{
if (!isspace(s[i]))
{
if (s[i]=='+' || s[i]=='-')
flag = s[i++]=='-'?-1:1;
while (i<s.size() && isdigit(s[i]))
{
num = num*10+s[i++]-'0';
if (num*flag<INT_MIN) return INT_MIN;
if (num*flag>INT_MAX) return INT_MAX;
}
break;
}
}
return num*flag;
}
};