【算法】String To Integer

题目要求:

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.

这是LeetCode中的第8题,剑指offer中涉及到的一道面试题,将String转化为Integer型,看似很简单,但是需要考虑的情况很多,需要比较细心。

首先字符串转换中遇见非数字字符的处理,字符串超出最大整型和最小整型怎么处理。开题遇到空格,用trim()去空格。+,-号只可能在去空格后第一位。中间遇到非数字字符,直接返回前一段字符,判断是否有效,并转换为整型。
代码如下:

/**
* 将字符串转化为整数
* @congrisheng
* @2017-3-12
*/
public static int StrToInt(String str){
    /*定义最大最小边界值*/
    int max = Integer.MAX_VALUE;
    int min = Integer.MIN_VALUE;

    if(str == null || str.length() == 0){
        return 0;
    }
    /*去掉字符串首尾的空格*/
    str = str.trim();
    /*如果首位是+,- 作为整数的符号*/
    boolean sign = false;
    if(str.charAt(0) == '-' || str.charAt(0) == '+'){
        if(str.charAt(0) == '-'){
            sign = true;
        }
        str = str.substring(1);
    }

    int len = str.length();
    /*定义为long型去储存结果*/
    long res = 0; 
    for(int i = 0; i < len; i++){
        char s = str.charAt(i);
        /*不是整数就中断*/
        if(s < '0' || s > '9'){
            break;
        }
        /*转换*/
        res = res*10 + (s - '0');
        /*超过阈值直接return*/
        if(!sign && res > max){
            return max;
        }
        if(sign && -res < min){
            return min;
        }
    }
    if(sign){
        res = -res;
    }
    /*转换为int型的数*/
    return (int)res;
}

From 《剑指offer》 Page12

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值