leetcode_8_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.

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'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)_第1张图片
附 教父里面的两句台词:
女人和小孩可以不细心,但男人不可以!
把意外当成是对个人尊严侮辱的人永远不会遭遇意外。

你可能感兴趣的:(leetcode,leetcode题解,BigInteger,String,leetcode,whitespace)