Thought:
Skip whitespace -> Check Sign -> Check Digit -> Check Overflow -> Result
When dealing with overflow, we could write neither
result * 10 > Integer.MAX_VALUE - temp nor
result * 10 + temp > Integer.MAX_VALUE
Because both of their left side might overflows which will lead to the wrong answer.
Code:
public class Solution {
public int atoi(String str) {
int i = 0, result = 0, sign = 1;
char c = ' ';
while (i < str.length()) {
c = str.charAt(i);
if (Character.isWhitespace(c)) {
i++;
}else if (c == '+' || c == '-' ) {
i++;
if( c == '-' ) sign = -1;
break;
}else if(Character.isDigit(c)){
break;
}else{
return 0;
}
}
while (i < str.length()) {
c = str.charAt(i);
if (!Character.isDigit(c)){
break;
}else{
int temp = Character.digit(c, 10);
if( result > (Integer.MAX_VALUE - temp)/10 ){
return sign < 0? Integer.MIN_VALUE: Integer.MAX_VALUE;
}else{
result = result * 10 + temp;
}
}
i++;
}
return sign * result;
}
}
No comments:
Post a Comment