-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtoi.cpp
More file actions
51 lines (50 loc) · 916 Bytes
/
Atoi.cpp
File metadata and controls
51 lines (50 loc) · 916 Bytes
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
/*Question:
Atoi
Asked in:Adobe,Nvidia ,Agilent systems ,Bloomberg ,Amazon, Apple, Microsoft ,Groupon.
Implement atoi to convert a string to an integer.*/
int Solution::atoi(const string A) {
string number="";
bool negative=false;
int i=0;
while(A[i]==' ')i++;
if(A[i]=='-')
{
negative=true;
i++;
}
if(A[i]=='+')
{
negative=false;
i++;
}
while('0'<=A[i]&&A[i]<='9')
{
number+=A[i];
i++;
}
if(number.size()>=10)
{
if(negative)
return INT_MIN;
else
return INT_MAX;
}
long ans=0;
for(int j=0;j<number.size();j++)
{
ans=ans*10+(number[j]-'0');
}
if(negative)
{
ans*=-1;
if(ans<INT_MIN)
return INT_MIN;
return ans;
}
else
{
if(ans<INT_MAX)
return ans;
return INT_MAX;
}
}