Approach #1 [Accepted]
Algorithm
For this problem we have to take care of the following:
- White spaces
- Signs
- Overflow
Java
public class Solution {
public static int myAtoi(String str) {
if(str.length()==0)
return 0;
StringBuilder sb=new StringBuilder();
int sign=1,i=0;
//removing leading white spaces
while (str.charAt(i)==' ')
i++;
//taking care of signs
if(str.charAt(i)=='+') {
sign = 1;
i++;
}
else if(str.charAt(i)=='-') {
sign = -1;
i++;
}
//extracting digits
while(i<str.length()) {
if(str.charAt(i)<'0'|| str.charAt(i)>'9') {
break;
}
else {
sb.append(str.charAt(i) - '0');
}
i++;
}
int total=0;
for(char ch: sb.toString().toCharArray())
{
int digit=Integer.parseInt(ch+"");
System.out.println(total);
//handling the overflow case
if(Integer.MAX_VALUE/10<total||Integer.MAX_VALUE/10==total && Integer.MAX_VALUE%10<digit )
{
return sign==1? Integer.MAX_VALUE:Integer.MIN_VALUE;
}
total=total*10+digit;
}
return total*sign;
}
}
Complexity Analysis
- Time complexity : O(n).