Leetcode #8 String to Integer (atoi) (E)

[Problem]

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.

 

[Analysis]

这题的要点只在于将corner cases考虑周全。实在无法通过OJ的话参考spoiler基本就没问题了。

 

[Solution]

public class Solution {
    public int atoi(String str) {
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        
        int sign = 1;
        int i = 0;
        if (str.charAt(0) == '+') {
            i++;
        } 
        
        if (str.charAt(0) == '-') {
            sign = -1;
            i++;
        }
        
        long result = 0;
        for (; i < str.length(); i++) {
            int digit = str.charAt(i) - '0';
            if (digit > 9 || digit < 0) {
                break;
            } else {
                if (result > Long.MAX_VALUE/10) {
                    break;
                }

                result *= 10;
                if (result > Long.MAX_VALUE - digit) {                    
                    break;
                }

                result += digit;
            }            
        }
        
        result = result * sign;
        if (result > Integer.MAX_VALUE) {
            result = Integer.MAX_VALUE;            
        } else if (result < Integer.MIN_VALUE) {
            result = Integer.MIN_VALUE;            
        }    
    
        return (int)result;        
    }
}

 

posted on 2015-10-06 01:43  张惬意  阅读(93)  评论(0编辑  收藏  举报