-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_to_integer_atoi.cpp
50 lines (42 loc) · 1.37 KB
/
string_to_integer_atoi.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//12ms, can be optimized
class Solution {
public:
int myAtoi(string str) {
return myAtoiAlg(str, 0);
}
private:
int myAtoiAlg(string str, const int start) {
if(start == str.size()) return 0;
if(str[start] == ' ') return myAtoiAlg(str, start+1);
if(str.size() -start== 1 &&( str[start] > '9' || str[start] < '0')) return 0;
bool sign;
if(str[start] >= '0' && str[start] <= '9'){
sign = true;
}
else if(str[start] == '+'){
sign = true;
str[start] = '0';
}
else if(str[start] == '-'){
sign = false;
str[start] = '0';
}
else return 0;
int ret = 0;
if(sign){
for(int i_ = start; i_< str.length(); ++i_){
if(str[i_] <'0' || str[i_] > '9') return ret;
if(sign && (int(0x7FFFFFFF) - str[i_] + '0')/10 <ret) return 0x7FFFFFFF;
ret = ret*10 + str[i_] - '0';
}
}
else{
for(int i_ = start; i_< str.length(); ++i_){
if(str[i_] <'0' || str[i_] > '9') return ret;
if(!sign && (int(0x80000000) + str[i_] - '0')/10 >ret) return 0x80000000;
ret = ret*10 - str[i_] + '0';
}
}
return ret;
}
};