[leetcode]_String to Integer (atoi)

非常考虑思维全面性的一道题,考验是否能够考虑本问题的方方面面。

题目:将一个string转换为int。实现函数atoi()的功能。

先应该明确atoi()有哪些特殊功能:(正常的正负数情况我就不列了)

input output
”+1“ 1
”   +   1“  0(error了)
”       1“ 1(前头只有空格是合法的)
”12b45“ 12(取前面的数字)
溢出 : ”2147483648“(负数情况同) 2147483647(MAX_VALUE)

 

类似我对atoi()的功能不熟的人来说,这道题就是不停WA的血泪史。每次要修正一次错误答案。

最终AC:

public int atoi(String str) {
        int len = str.length();
        long num = 0;
        //用long型存储,以处理溢出的情况
        int ifNegative = 1;
        boolean numStatus = false;
        for(int i = 0 ; i < len ; i++){
            char ch = str.charAt(i);
            if(numStatus && (ch < '0' || ch > '9')) break;
            else if(numStatus && ch >= '0' && ch <= '9'){
                num = num * 10 + (ch - '0');
            }else if(!numStatus && ch != '-' && ch != '+' && (ch < '0' || ch > '9')){
                num = 0;
                break;
            }else if(!numStatus && ch == '-'){
                numStatus = true;
                ifNegative = -1;
            }else if(!numStatus && ch == '+'){
                numStatus = true;
            }else if(!numStatus && ch >= '0' && ch <= '9'){
                numStatus = true;
                num = num * 10 + (ch - '0');
            }
            
        }
        num *= ifNegative;
        
        int result = 0;
        if(num > Integer.MAX_VALUE) result = Integer.MAX_VALUE;
        else if(num < Integer.MIN_VALUE) result = Integer.MIN_VALUE;
        else result = (int) num;
        
        return result;
        
    }
原文地址:https://www.cnblogs.com/glamourousGirl/p/3730164.html