码迷,mamicode.com
首页 > 其他好文 > 详细

String to Integer (atoi)

时间:2015-05-13 10:06:11      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/77rousongpai/p/4499355.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!