3ms JAVA REALLY EASY to understand !

• ``````public class Solution {
public int myAtoi(String str) {
double result = 0;
int POrN = 1;
int count = 0;
char[] charArr = str.toCharArray();
for(char c:charArr){
count ++;
if( c >='0' && c <='9' ){
result *= 10;
result += ( c - '0');
}else if( c == '-' && count == 1){
POrN = -1;
}else if( c == '+' && count == 1){
POrN =  1;
}else if( c == ' ' && count == 1){
count --;
}else{
break;
}

}
if( result > Integer.MAX_VALUE ){
if(POrN == 1)
return Integer.MAX_VALUE;
else
return Integer.MIN_VALUE;
}else{
return (int)(result * POrN);
}
}
}
``````

• @frankpeter really consice, thank u!

• @frankpeter What does the variable "POrN" mean and do?

• @DanielMan97 It means positive or negative

• There is a problem with only testing (result > Integer.MAX_VALUE), since (Integer.MAX_VALUE != abs(Integer.MIN_VALUE)).

Some numbers:

• -(Integer.MAX_VALUE + 1) == Integer.MIN_VALUE
• -(Integer.MAX_VALUE + .5) == Integer.MIN_VALUE
• -(Integer.MAX_VALUE + .0000001) != Integer.MIN_VALUE
• Integer.MAX_VALUE + .0000001 == Integer.MAX_VALUE
• Integer.MAX_VALUE + .5 != Integer.MAX_VALUE

• @CaseyCutler If the input number is a decimal,my algorithm takes only the integer portion of it.

• 37ms --10/16/2016

• Nice solution! But could you explain what is the
else{
break;
}
for in for loop? What condition it wants to prevent from?

• @laahaa characters other than 0-9 ,+, - , space or if +,- , space are not first characters then we can break the loop. Hope that helps

• It's an amazing solution!
but the variable POrN seems useless.

• @caterby POrN is used to handle + and - characters in the string. It is needed.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.