0%

LeetCode-008-String to Integer (atoi)

Problem

实现C++的atoi()函数
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: $$ [−2^{31}, 2^{31} − 1] $$. If the numerical value is out of the range of representable values, INT_MAX $$ 2^{31}-1 $$ or INT_MIN $$ -2^{31} $$ is returned.

Examples:

Input:“42”
Output:**42
**Input:
“ -42”
Output:-42
Input:“words and 987”
**Output:**987

Solutions

  • 没啥思维量,就是简单的遍历每个字符,然后设置两个flag,一个用于判断有没有到数字部分,第二个判断是不是负数,如果没到数字部分,就要分情况讨论,如果到了数字部分,判断到没到非数字,到了就退出,没到就每个数字加到结果上

C++ Codes

每个字符遍历过去的方法,12ms,8.4MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int myAtoi(string str) {
long long tmp = 0;
int n = str.length();
if(n==0)return 0;
bool flag = false;//是否到数字部分
int flag2 = 1;//负数标志,有就变为-1

for(int i=0;i<n;i++){
//已经开始数字部分的情况,即flag = true
if(tmp>INT_MAX)break;
if(flag && (str[i]<'0' || str[i]>'9')) break;
if(flag) tmp = tmp*10+str[i]-'0';

//还没到数字的情况,前面那部分,分为空格、非数字非符号、数字或正负号
if(!flag && str[i]==' ') continue;
if(!flag && str[i]!='+' && str[i]!='-' && (str[i]<'0' || str[i]>'9') )
return 0;
if(!flag && (str[i]=='+' || str[i]=='-'|| (str[i]>='0'&&str[i]<='9'))){
flag = true;
if(str[i]=='-')flag2 = -1;
if(str[i]=='+'||str[i]=='-')continue;
tmp = tmp*10+str[i]-'0';
}
}

tmp*=flag2;
if(tmp>INT_MAX) return INT_MAX;
if(tmp<INT_MIN) return INT_MIN;
return (int)tmp;
}
};

Python Codes

借用了HazzaCheng的代码,这道题用python解简直作弊..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def myAtoi(self, s):
ls = list(s.strip())
if len(ls) == 0:
return 0

sign = -1 if ls[0] == '-' else 1
if ls[0] in ['-', '+']:
del ls[0]
res, i = 0, 0
while i < len(ls) and ls[i].isdigit():
res = res * 10 + ord(ls[i]) - ord('0')
i += 1
return max(-2 ** 31, min(sign * res, 2 ** 31 - 1))

总结

  • 要注意各种情况的判断
  • 就算用了long long作为中转,在循环中也要判断是否已经超过int表示范围,提前break,可能出现longlong都无法表示的测试
  • 注意空串
  • 注意前面的符号
  • 不应该进行的操作及时continue掉
  • 还是会出现’+’号的