字符串转换为整数 String to Integer (atoi)

问题:

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.

解决:

考虑一个字符串是不是数字时需要考虑的特殊字符有空格 ‘ ’, 小数点 '.', 自然数 'e/E', 还要加上正负号 '+/-"

【函数说明】atoi() 函数会扫描 str 字符串,跳过前面的空白字符(例如空格,tab缩进等),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。

【返回值】返回转换后的整型数;如果 str 不能转换成 int 或者 str 为空字符串,那么将返回 0。如果超出Integer的范围,将会返回Integer最大值或者最小值。

【处理思路】按照函数说明来一步步处理。首先判断输入是否为null。然后使用trim()函数删掉空格。判断是否有正负号,做一个标记。返回的是整型数,可以使用double来暂存结果。按位来计算出结果。如果遇到非数字字符,则返回当前结果。加上前面的正负号。结果若超出了整形范围,则返回最大或最小值。最后返回处理结果。

在discuss上看到的测试用例:

InputOutputExpected
"    b11228552307"21474836470
"+-2"20
"  -0012a42"0-12
"   +0 123"1230
" 10522545459"19326108672147483647

① 直接转化,使用一个标记flag表示是否存在+-号。

class Solution { //39ms
    public int myAtoi(String str) {
        if(str == null || str.length() == 0) return 0;
        str = str.trim();
        int flag = 1;
        int i = 0;
        double res = 0;
        if(str.charAt(0) == '-'){
            flag = -1;
            i ++;
        }else if(str.charAt(0) == '+'){
            i ++;
        }
        while(i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
            res = res * 10 + str.charAt(i) - '0';
            i ++;
        }
        if(flag == -1) res = res * flag;
        if(res > Integer.MAX_VALUE) res = Integer.MAX_VALUE;
        if(res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        return (int) res;
    }
}

② 进化版,还是用上面一种方法比较好。。。

public class Solution { //37ms
    public int myAtoi(String str) {
        int i = 0;
        int sign = 1;
        int res = 0;
        //1. 空字符串
        if(str.length() == 0) return 0;
        //2. 移除空格
        while(str.charAt(i) == ' ' && i < str.length())
            i ++;
        //3. 处理正负号
        if(str.charAt(i) == '+' || str.charAt(i) == '-'){
            sign = str.charAt(i) == '+' ? 1 : -1;
            i ++;
        }
        //4. 转换数字,并处理溢出
        while(i < str.length()){
            int digit = str.charAt(i) - '0';
            if(digit < 0 || digit > 9) break;
            if(Integer.MAX_VALUE / 10 < res || Integer.MAX_VALUE / 10 == res && Integer.MAX_VALUE % 10 < digit)
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            res = 10 * res + digit;
            i ++;
        }
        return res * sign;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1523594

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值