3.3 String to Integer(atoi)

按照leetcode戴的C++版本对照写的java版。还需要再练习单独写。

public class Solution {
    public int atoi(String str) {
        if(str.length() == 0 || str == null) return 0;
        int sign = 1;
        int i = 0;
        int num = 0;
        while(str.charAt(i) == ' ' && i < str.length()){
                i++;
        }
        if(str.charAt(i) == '+'){
            i++;
        }
        else if (str.charAt(i) == '-'){
            sign = -1;
            i++;
        }
        for(; i < str.length(); i++){
            if(str.charAt(i) <'0' || str.charAt(i) > '9') break;
            else if (num > Integer.MAX_VALUE/10 || (num == Integer.MAX_VALUE/10 && (str.charAt(i) - '0' > Integer.MAX_VALUE%10))){
                return sign == -1? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            num = num * 10 + str.charAt(i) - '0';
        }
        return sign * num;
    }
}


我第二次写的代码:注意:

记得要考虑符号

把char 转换成int,不能用Integer.parseInt (char), 而要用char - '0' 

public class Solution {
    public int atoi(String str) {
        int result = 0;
        if(str == null || str.length() == 0){
            return result;
        }
        int i = 0;
        while(str.charAt(i) == ' ' && i < str.length()){//ignore the preceeding spaces
            i++;
        }
        for(;i < str.length(); i++){
            char c = str.charAt(i);
            if(c < '0' || c > '9') continue;
            int num = Integer.parseInt(c);
            result = result * 10 + num;
        }
        if(result > Integer.MAX_VALUE){
            result = Integer.MAX_VALUE;
        }
        else if(result < Integer.MIN_VALUE){
            result = Integer.MIN_VALUE;
        }
        return result;
    }
}


http://blog.csdn.net/linhuanmars/article/details/21145129

的解法不同于上面的:对吗?e.g. Integer.MAX_VALUE = 55, 那res = 56时,我们应该返回MAX_VALUE。但按这个程序不返回MAX_VALUE.

if(isNeg && res>-((Integer.MIN_VALUE+digit)/10))  
            return Integer.MIN_VALUE;  
else if(!isNeg && res>(Integer.MAX_VALUE-digit)/10)  
            return Integer.MAX_VALUE;  



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值