LeetCode #8 String to Integer (atoi) 字符串转数字 解题小节

1 原题

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.

2 题目理解

这题的意思是,给定一个用String表示的数字,然后需要你转化为一个真正的int呢。
Leetcode标记的难度是Easy,但是我觉得这道题陷阱很多,要注意到很多很多特别的地方,我就这么提几个:

0、我做的时候给定的String一定是合法的数字,这点很重要,因为我往后刷遇到过类似问题,这边给定的是合法的,所以部分处理就很简单了,特别是空格。
1、注意前后的空格,输入的数字可能会留空,所以往前往后都需要去空格。
2、需要考虑正负号,这个是合法的
3、注意int的最大值和最小值的绝对值大小不一样,所以如果在计算的时候是暂时抛弃了符号,一位一位的前进的,需要特别注意这个问题。
4、注意不要溢出

总之流程就是:
1、去除空格
2、检查是否正反符号
3、转换数字整体,并时刻检查是否溢出,关于溢出的问题的解决,可以看我前面的博客,这里我选用了long解决

3 AC解 Java

public class Solution {
    /**
     * 倘若某个数超过了2147483647则会变为负数,反过来一样*/
    public int myAtoi(String str) {
        if(str.equals(""))
            return 0;
        char chars[]=str.toCharArray();
        long result=0,maxs=Integer.MAX_VALUE,mins=-1*(long)Integer.MIN_VALUE;
        int i=0,flag=1;
        while(chars[i]==' '){
            i++;
        }
        if(chars[i]=='-'){
            flag=-1;
            i++;
        }
        else if(chars[i]=='+'){
            flag=1;
            i++;
        }
        while(i<str.length()){
            if(chars[i]==' ')
                return (int)result*flag;
            if( chars[i]>'9' || chars[i]<'0' )
                return (int)result*flag;
            result=result*10+(chars[i++]-'0');
            if(flag==1 && result>maxs ){
                return (int)maxs*flag;
            }
            if(flag==-1 && result>mins ){
                return (int)mins*flag;
            }
        }
        return (int)result*flag;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值