【LeetCode】12.String to Integer (atoi)

比较简单的题目,但是还是提交了好几遍才A掉一一!

需要考虑的:

(1)字符串前面的空格 trim()或者while()

(2)正负符号

(3)只取最前面的数字字符,一旦出现非数字字符后面即使有数字也不考虑了

(4)空字符串 

(5)溢出:最大数最小数两种

      遗忘了一种情况 ,出现了下面的错误。解决方法是:

加上|| (sum>=1000000000)

Submission Result: Wrong Answer

Input: " -11919730356x"
Output: 965171532
Expected: -2147483648

正确代码如下:

public class Solution {
    public int atoi(String str) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
       
        int sum=0,temp=0;
        int i=0;
        boolean negtive=false;
        boolean over=false;
        final int INT_MAX=2147483647;
        final int INT_MIN=-2147483648;
        str=str.trim();
     //while (i < str.length() && str.charAt(i) == ' ') i++; if(str.length()==0) return 0; if(str.charAt(i)=='-'){ negtive=true; i++; } if(str.charAt(i)=='+'){ i++; } while(i<str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){ temp = str.charAt(i)-'0'; if (sum >= 214748364) { if ((!negtive && temp>=7) || negtive && temp>=8 || (sum>=1000000000)) { over = true; break; } } sum=sum*10+temp; i++; } if(over==true && negtive==true) return INT_MIN; if(over==true && negtive==false) return INT_MAX; if(negtive) return -1*sum; else return sum; } }
原文地址:https://www.cnblogs.com/guozhiguoli/p/3371100.html