-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringToInteger.cpp
More file actions
55 lines (54 loc) · 1.45 KB
/
stringToInteger.cpp
File metadata and controls
55 lines (54 loc) · 1.45 KB
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
51
52
53
54
55
/*
* stupid problem, see description on website
*/
class Solution {
public:
int myAtoi(string str) {
transform(str.begin(), str.end(),str.begin(), ::toupper);
const char * p = str.c_str();
bool is_negative = false;
uint64_t r = 0;
int res=0;
int radix = 10;
//limits:not start with 0; all characters are digit num; first character can be '-'
while(*p!=NULL){
if(*p==' '){
p++;
continue;
}
break;
}
if(*p == '-'){
is_negative = true;
p++;
}else if(*p == '+')
p++;
cout<<"begin with :"<<*p<<endl;
const char *p2 = p;
while(*p2 != NULL){
if(*p2 >'9' || *p2 < '0'){
cout<<"invalide string:"<<(int)*p2<<"p="<<(int)(*p)<<endl;
break;
//return 0;
}
p2++;
}
cout<<"p="<<*p<<",p2="<<*p2<<endl;
while(p<p2){
int ip=(int)(*p-48);
r = r*radix + ip;
if(r>INT_MAX)
if(!is_negative)
return INT_MAX;
else if(-r < INT_MIN)
return INT_MIN;
cout<<bitset<36>(r)<<endl;
res = r;
cout<<"res="<<res<<endl;
p++;
}
if(is_negative)
return -res;
return res;
}
};