现在的位置: 首页 > 综合 > 正文

String to Integer

2014年09月05日 ⁄ 综合 ⁄ 共 638字 ⁄ 字号 评论关闭

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.
        if(str == null || str.trim().length() == 0)
            return 0;
        
        // remove whitespace
        str = str.trim();
        boolean positive = true;
        char first = str.charAt(0);
        if(first == '+' || first == '-') {
            str = str.substring(1);
            if(first == '-')
                positive = false;
        }
                
        long result = 0; // long instead of int
        for(int i = 0; i < str.length(); i++){
            char cur = str.charAt(i);
            if(cur < '0' || cur > '9')
                break;
            result = result*10 + (cur-'0');
        }
        
        result = (positive == true) ? result : 0 - result;
        
        if(result < Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        else if(result > Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        else
            return (int) result;
    }

抱歉!评论已关闭.