-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_to_integer(atoi).cpp
More file actions
63 lines (53 loc) · 1.3 KB
/
string_to_integer(atoi).cpp
File metadata and controls
63 lines (53 loc) · 1.3 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
56
57
58
59
60
61
62
63
#include<bits/stdc++.h>
using namespace std;
int atoi(string s){
long long int x=0;
int sign=0,flag=0,i=0;
for(i=0;i<s.length();i++){
if(s[i]=='-' && i!=s.length()-1){
int z=(int)s[i+1];
if( 48<=z && z<=57 ){
sign=1;
}else if(s[i+1]=='+' ||s[i+1]=='-'){
return 0;
}
}else if(s[i]=='+' && i!=s.length()-1){
if(s[i+1]=='-' || (int)s[i+1]==32 || s[i+1]=='+'){
return 0;
}
}else if(48<=(int)s[i] && (int)s[i]<=57){
flag=1;
break;
}else if((int)s[i]>57 || ((int)s[i]<48 && !((int)s[i]==32) && !((int)s[i]==43))){
return 0;
}
}
//cout<<"yes"<<endl;
if(flag==1){
while(s[i]!=' ' && i<s.length() && (int)s[i]<=57 && (int)s[i]>=48){
int z=(int)s[i];
x=x*10+(z-48);
if(x>INT_MAX && sign==0){
return INT_MAX;
}else if(x>INT_MAX && sign==1){
return INT_MIN;
}
i++;
//cout<<x<<" "<<i<<endl;
}
}
if(sign==1){
x=-x;
}
if(x>INT_MAX){
return INT_MAX;
}else if(x<INT_MIN){
return INT_MIN;
}
return x;
}
int main(){
string s=" -42";
cout<<atoi(s);
return 0;
}