public static int myAtoi(String str) { if (str == null || str.length() == 0||str.trim().length()==0) { return 0; } str = str.trim();//去除空格 char flag = str.charAt(0); int start = 0; int sign = 1; if (flag == '+') { sign = 1; ++start; }else if (flag == '-') { sign = -1; ++start; }else if(!Character.isDigit(str.charAt(0))){ return 0; } long result = 0; char[] chars = str.toCharArray(); long res=0; for (int i = start; i < chars.length; i++) { if (Character.isDigit(chars[i])) { result = result*10 +chars[i]-'0'; if(res>result){//判斷溢出的情況 result=sign>0?Integer.MAX_VALUE:Integer.MIN_VALUE; return (int)result; } res=result; if(result<0&&sign*result<0){ return Integer.MAX_VALUE; }else if(result<0&&sign*result>0){ return Integer.MIN_VALUE; } }else{ break; } } if (sign*result > (Math.pow(2, 31)-1)) { return Integer.MAX_VALUE; } if ( sign*result < (-1*Math.pow(2, 31))) { return Integer.MIN_VALUE; } return sign*(int)result; }