forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solution to #issue pezy#23 : String to Integer (atoi) is not found (404)
Have not added any Readme file since Readme files are in different language. Since main Readme file doesn't contain this problem, I have labeled it as 711.
- Loading branch information
1 parent
1756256
commit 00960ad
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
class Solution { | ||
public: | ||
bool isOverflow(long long a, long long b){ | ||
long long res=a*10+b-48; | ||
if(res>INT_MAX) | ||
return true; | ||
return false; | ||
} | ||
|
||
int myAtoi(string s) { | ||
int c=0; | ||
bool isminus=0; | ||
bool nostart=0; | ||
for(int i=0;i<s.size();i++){ | ||
|
||
if(s[i]==32){ | ||
if(!nostart) | ||
continue; | ||
else | ||
break; | ||
} | ||
else if(s[i]==43){ | ||
if(!nostart) | ||
nostart=1; | ||
else | ||
break; | ||
} | ||
else if(s[i]==45){ | ||
if(nostart) | ||
break; | ||
else{ | ||
isminus=1; | ||
nostart=1; | ||
} | ||
} | ||
else if((s[i]<48)||s[i]>57){ | ||
break; | ||
} | ||
else{ | ||
nostart=1; | ||
if(isOverflow(c,s[i])){ | ||
if(isminus){ | ||
c=INT_MIN; | ||
isminus=0; | ||
} | ||
else{ | ||
c=INT_MAX; | ||
} | ||
break; | ||
} | ||
|
||
else{ | ||
c=c*10+(s[i]-48); | ||
} | ||
|
||
} | ||
} | ||
|
||
if(isminus){ | ||
c=c*-1; | ||
} | ||
|
||
return c; | ||
} | ||
}; |