程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetcode_8_String to Integer (atoi)

leetcode_8_String to Integer (atoi)

編輯:C++入門知識

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();
    }

結果:


附教父裡面的兩句台詞: 女人和小孩可以不細心,但男人不可以!
把意外當成是對個人尊嚴侮辱的人永遠不會遭遇意外。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved