8,String to Integer (atoi)

来源:互联网 发布:mac玩使命召唤 编辑:程序博客网 时间:2024/06/06 04:10

Implement atoi to convert a string to an integer.//实现atoi函数,实现字符串到整形的转换

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.

题目分析:这是一道算法思想很简单的题目,属于细节题,其中藏着很多陷阱。

1.数字前面有空格 如s=“    123456”
2.数字前出现了不必要或多于的字符导致数字认证错误,输出0   如s=“   b1234”  ,s=“  ++1233” , s=“ +-1121”
3.数字中出现了不必要的字符,返回字符前的数字 如s=“   12a12” , s=“ 123  123”
4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648  超过了正数的输出2147483647

程序如下:

public class Solution {    public int atoi(String str){    //考虑""的情况        if(str.length()==0)            return 0;        //结果        int result=0;        //符号        int sign=1;        int i=0;        //去除前面的空格        while(str.charAt(i)==' ') ++i;        //判断符号        if(str.charAt(i)=='-')        {            sign=-1;            ++i;        }        else if(str.charAt(i)=='+')        {            sign=1;            ++i;        }        for(;i<str.length();++i)        {            if('0'<=str.charAt(i)&&str.charAt(i)<='9')            {            //判断是否溢出                if(result>Integer.MAX_VALUE/10||                    (result==Integer.MAX_VALUE/10&&                        str.charAt(i)-'0'>Integer.MAX_VALUE%10))                        return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE;                result*=10;                result+=str.charAt(i)-'0';            }            else                return result*sign;        }        return result*sign;    }}


从程序上看出,正确的格式是(第一个非空字符且必须为+/-/数字)到(下一个非数字的字符)

如"  +0012 123" 正确输出为12

"+-12" 正确输出为0,因为+为开始,-为结束,中间只有0的结果


0 0
原创粉丝点击