String to Integer (atoi)

public class Solution {
    public int myAtoi(String str) {
        if (str == null) {
            return 0;
        }
        
        int res = 0;
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        int i = 0;
        boolean isNeg = false;
        if (str.charAt(0) == '-') {
            i++;
            isNeg = true;
        }
        if (str.charAt(0) == '+') {
            i++;
        }
        
        while (i < str.length()) {
            if (str.charAt(i) > '9' || str.charAt(i) < '0') {
                break;
            }
            int digit = (int)(str.charAt(i) - '0');
            if (isNeg && res > -((Integer.MIN_VALUE + digit)/10)) {
                return Integer.MIN_VALUE;
            }
            if (!isNeg && res > (Integer.MAX_VALUE - digit) /10) {
                return Integer.MAX_VALUE;
            }
            res = res*10 + digit;
            i++;
        } 
        return isNeg?(-res) : res;
    }
}

 

posted on 2015-05-13 09:08  kikiUr  阅读(85)  评论(0编辑  收藏  举报