classSolution{publicintmyAtoi(String s){finalint len = s.length();int index =0;// No digitsif(len ==0)return0;// Ignore white spaceswhile(index < len && s.charAt(index)==' '){++index;}// Prevent overflowif(index >= len)return0;// Determine signchar ch = s.charAt(index);boolean isNegative = ch =='-';// If sign appears, move indexif(isNegative || ch =='+'){++index;}// -2147483648 to 2147483647finalint maxLimit =Integer.MAX_VALUE/10;int result =0;// Iterate until the end or non digit showswhile(index < len &&isDigit(ch = s.charAt(index))){int digit = ch -'0';// Get current digit// Out of bound, especially check Integer overflowif(result > maxLimit ||(result == maxLimit && digit >7)){return isNegative ?Integer.MIN_VALUE:Integer.MAX_VALUE;}// Update the result
result =(result *10)+ digit;++index;}return isNegative ?-result : result;}// Determine if a character is a digitprivatebooleanisDigit(char c){return c >='0'&& c <='9';}}