-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added the solution to the question in Java.
- Loading branch information
1 parent
cd14fb7
commit 600120d
Showing
1 changed file
with
25 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,25 @@ | ||
/* This solution uses the concept and strings and the functions concerning it. */ | ||
|
||
Class answer{ | ||
public int atoi(String s){ | ||
if(s==null) return 0; //in case the String is empty | ||
s=s.trim(); //removes leading spaces | ||
if(s.length()==0) return 0; | ||
int sign=-1; | ||
long ans=0; //taking long since integer might exceed the max/min | ||
int max=Integer.MAX_VALUE; | ||
int min=Integer.MIN_VALUE; | ||
if(s.charAt(0)=='-') sign = -1; | ||
int i = (s.charAt(0)=='+' || s.charAt(0)=='-') ? 1 : 0; //skips an index if a sign is there. | ||
while(i<s.length()){ | ||
if(!Character.isDigit(s.charAt(i))) break; //returns 0 if first index is not a digit and breaks out of the loop. | ||
ans = ans * 10 + (s.charAt(i)-'0'); | ||
if(sign == -1 && ans*-1 < MIN) return MIN; //if ans exceeds min then return min according to the question. | ||
if(sign == 1 && ans > MAX) return MAX; //if ans exceeds max then return max according to the question. | ||
i++; | ||
} | ||
return (int)ans*sign; | ||
} | ||
} | ||
|
||
|