LeetCode-StringtoInteger(atoi)

12/12/2015来源:Java教程人气:1190

题目:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this PRoblem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

思路:

基本运算;注意判断乘和加的溢出。

package manipulation;

public class StringToInteger {

    public int myAtoi(String str) {
        int len;
        if (str == null || (len = str.length()) == 0) return 0;
        int pos = 0;
        int sign = 1;
        int res = 0;
        while (Character.isWhitespace(str.charAt(pos))) ++pos;
        if (str.charAt(pos) == '+') {
            ++pos;
        } else if (str.charAt(pos) == '-') {
            ++pos;
            sign = -1;
        }
        
        while (pos < len && Character.isDigit(str.charAt(pos))){
            int value = str.charAt(pos) - '0';
            int preRes = res;
// We use Math.abs here because on the second time, res will become positive if sign == -1 res
= Math.abs(res) * 10 * sign; if (res/(10 * sign) != Math.abs(preRes)) { return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; } preRes = res; res = res + sign * value; if (sign == 1 && res < preRes) return Integer.MAX_VALUE; if (sign == -1 && res > preRes) return Integer.MIN_VALUE; ++pos; } return res; } public static void main(String[] args) { // TODO Auto-generated method stub String str = "-123"; StringToInteger sti = new StringToInteger(); System.out.println(sti.myAtoi(str)); } }

代码更简洁一些:

package manipulation;

public class StringToInteger {

    public int myAtoi(String str) {
        int len;
        if (str == null || (len = str.length()) == 0) return 0;
        int pos = 0;
        int sign = 1;
        int res = 0;
        while (Character.isWhitespace(str.charAt(pos))) ++pos;
        if (str.charAt(pos) == '+') {
            ++pos;
        } else if (str.charAt(pos) == '-') {
            ++pos;
            sign = -1;
        }
        
        while (pos < len && Character.isDigit(str.charAt(pos))) {
            int value = str.charAt(pos) - '0';
            if (sign == 1 && res > (Integer.MAX_VALUE - value) / 10) 
                    return Integer.MAX_VALUE;            
            
            if (sign == -1 && (-res < (Integer.MIN_VALUE + value) / 10)) 
                    return Integer.MIN_VALUE;            
        
            res = res * 10 + value;
            ++pos;
        }
        
        return sign > 0 ? res : -res;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str = "-2147483648";
        StringToInteger sti = new StringToInteger();
        System.out.println(sti.myAtoi(str));
        // -(INT_MIN_VALUE) is still INT_MIN_VALUE 
        int x = -2147483648;
        System.out.println(-x);
    }

}