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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

spoilers alert… click to show requirements for atoi.

Subscribe to see which companies asked this question.

题目的意思是给出参数String类型 转化为int类型的。-123gs345

结果是-123 ,同时要考虑边界值,此题很简单,但是想要写对却不是那么容易,解题的思路自然是循环字符串,字符串可以以“-”“+”开头,代表正负数,用一个变量存起来这个数是正还是负,对字符串进行截取之后的结果可以循环,如果某一个字符是数字,则之前的结果*10 加上这个数字,如果字符不是数字则直接返回,但是要注意几点:
1,注意边界值的验证。
2,注意判断不要造成溢出。

Java代码:

public static int myAtoi(String str) {
        if(str==null||"".equals(str.trim()))
            return 0;
        Long result=(long) 0;
        str=str.trim();
        boolean  flag=false;
        if(str.startsWith("+")||str.startsWith("-")){
            if(str.startsWith("-")){
                flag=true;
            }
            str=str.substring(1, str.length());
        }
        for(int i=0;i<str.length();i++){
            char strTemp=str.charAt(i);
            if("0123456789".contains(String.valueOf(strTemp))){
                if("0123456789".contains(String.valueOf(strTemp))){
                    if(flag){
                        result = result*10-Integer.parseInt(String.valueOf(strTemp));
                        if(Integer.MIN_VALUE>result){
                            return Integer.MIN_VALUE;
                        }
                    }else{
                        result = result*10+Integer.parseInt(String.valueOf(strTemp));
                        if(Integer.MAX_VALUE<result){
                            return Integer.MAX_VALUE;
                        }
                    }
                }else{
                    return result.intValue();
                }
            }else{
                return result.intValue();
            }
        }
        return result.intValue();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专注网赚的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值