2015年6月6日星期六

[LeetCode] String to Integer (atoi)

Problem:

Implement atoi to convert a string to an integer.

Code:

public class Solution {
    public int atoi(String str) {
        if (str == null || str.length() < 1) {
            return 0;
        }
        str = str.trim();
        int i = 0;
        double result = 0;
        boolean isPositive = true;
        if (str.charAt(0) == '-') {
            isPositive = false;
            i = 1;
        } else if (str.charAt(0) == '+') {
            i = 1;
        }
        
        for (; i < str.length(); i++) {
            int tmp = charToInt(str.charAt(i));
            if (tmp == -1) {
                break;
            }
            result *= 10;
            result += tmp;
        }
        result = isPositive == false ? -result : result;
        if (result > Integer.MAX_VALUE) 
            return Integer.MAX_VALUE;
        else if (result < Integer.MIN_VALUE) 
            return Integer.MIN_VALUE;
        return (int)result;
    }
    
    public int charToInt(char a) {
        if (a >= '0' && a <= '9') 
            return a - '0';
        return -1;
    }
}

没有评论:

发表评论