String to Integer (atoi), Leetcode 解题笔记

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.

这道题要考虑的情况很多,而且很多陷阱,虽然思路不难,但是不容易做对。
要考虑的情况有:
1. 空String
2. 开头的空格
3. 正负符号 陷阱:注意有可能出现”+-356″的情况
4. 最大最小值 陷阱:有可能出现”1000000001″的情况
5. 尾部的非数字字符

代码如下:

public class Solution {
    public int atoi(String str) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int len = str.length();
        int index = 0;
        int sign = 1;
        int result = 0;
        
        if(len == 0)
            return result;
            
        while(index < len && str.charAt(index) == ' '){
            index++;
        }
        
        if(index < len && str.charAt(index) == '-'){
            sign = -1;
            index++;
        }
        else if(index < len && str.charAt(index) == '+'){
            index++;
        }
        else{}
        while(index < len && str.charAt(index)>='0' && str.charAt(index)<='9'){
            int d = str.charAt(index) - '0';
            if(result >= 214748364){
                if(sign == 1 && (d >= 7 || result > 1000000000)){
                    return Integer.MAX_VALUE;
                }
                if(sign == -1 && (d >= 8 || result > 1000000000)){
                    return Integer.MIN_VALUE;
                }
            }
            result = result*10 + d;
            index++;
        }
        
        return sign*result;
    }
}

总结,几个注意事项,判断一个字符是否为数字,可用代码中的方法,判断 ‘0’ <= c <= '9',也可利用Character.isDigit(c)的方法。
Java的最大整数值为2147483647,最小整数值为-2147483648,应当牢记。

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s