码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_8_String to Integer (atoi)

时间:2015-01-28 09:42:40      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:biginteger   string   leetcode   whitespace   

描述:

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.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

思路:

思路是很简洁的,但正负号,空格包括中间和字符串的开始和结尾的字符,字符串溢出,整数表示的最大数和负数能表示的最小数。。。。

编程让人变的更加严谨,目测还有很大的提升空间。

代码:

 public static int atoi(String str) {
        BigInteger integer=new BigInteger("0");
        if(str==null)
        	return 0;
        str=str.trim();
        if(str.equals(""))
        	return 0;
        int len=str.length();
        int flag=0;
        if(str.charAt(0)=='-')
        	flag=-1;
        else if(str.charAt(0)=='+')
        	flag=1;
        int i=0;
        if(flag!=0)
            i=1;
		if(str.charAt(i)>'9'||str.charAt(i)<'0')
			flag=-2;
        for(int j=i;j<len;j++)
        {
        	if(str.charAt(j)>'9'||str.charAt(j)<'0')
        		break;
        	integer=integer.multiply(BigInteger.valueOf(10)).add(BigInteger.valueOf(str.charAt(j)-'0'));
        }
        if(flag==-2)return 0;
        if(flag==-1)
        {
        	integer=integer.multiply(BigInteger.valueOf(-1));
        	if(integer.compareTo(BigInteger.valueOf(-2147483648))<0)
        		return -2147483648;
        }else if(integer.compareTo(BigInteger.valueOf(2147483647))>0)
        {
        	return 2147483647;
        }
        return integer.intValue();
    }

结果:

技术分享
教父里面的两句台词:
女人和小孩可以不细心,但男人不可以!
把意外当成是对个人尊严侮辱的人永远不会遭遇意外。

leetcode_8_String to Integer (atoi)

标签:biginteger   string   leetcode   whitespace   

原文地址:http://blog.csdn.net/mnmlist/article/details/43225545

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!