LeetCode--8 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.

二、算法思路

将字符串转化为int,主要考虑以下几种特殊情况:1.字符串前后的空格问题;2.正负号问题;3.字符串中非1-9的字符处理;4.超出int范围的问题

三、Java代码

public class Solution {
    public int myAtoi(String str) {
        if(str==null||str.equals("")){
            return 0;
        }
        boolean flag=false;
        int result=0;
        str=str.trim();
        if(str.charAt(0)=='-'){
            flag=true;
            str=str.substring(1);
        }else if(str.charAt(0)=='+'){
            str=str.substring(1);
        }
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)<'0'||str.charAt(i)>'9')
                break;
            int tempstr=(int)(str.charAt(i)-'0');
            int tempresult=result*10+tempstr;
           // result+=((int)(str.charAt(i)-'0'))*10*str.length;
            if((tempresult-tempstr)/10!=result||tempresult<0){
              
                    if(flag)
                        return Integer.MIN_VALUE;
                    else 
                        return Integer.MAX_VALUE;
                
            }
            result=tempresult;
        }
        if(flag){
            result*=(-1);
        }
        return result;
    }
}
至于为什么会在判断是否超出int范围是计算tempresult<0;以四位二进制数为例,6(0110)+2(0010)=-8(1000),如果只是通过前面的(tempresult-tempstr)/10!=result来判断,-8(1000)+(-2)(1110)=6(0110),因此必须加上tempresult<0。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值