[LeetCode][8]String to Integer (atoi)解析與模仿Java源碼實現 -Java實現

Q:

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.

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.


A:
以下解法和代碼沒有借閱以往任何資料,如果有更好的解法請在評論區留言

這題大概意思,就是讓我們實現atoi,也就是把一個String轉化成數字返回而已,在java中我們直接String.valueOf()就好了。有幾個hint說要注意所有的輸入的可能性。再往下看有一個Requirements for atoi:

1、可能有空格

2、正負號,而且可能有不止一個正負號

3、空值

4、超出int範圍

5、沒有顯示內容返回0,超出範圍顯示INT_MAX和INT_MIN

我一看這一題我就笑了。。。不就是昨天我們說的源碼嗎?昨天我們使用了位運算中間就參考了以前看過的部分源碼。只不過是昨天是從integer到string。今天反過來而已,不過今天這要求真夠多的。

在java源碼中,大致是先驗證了第一個字符是不是正負號,不是的話或者只含正負號就跑異常了,然後就開始遍歷呀,轉化呀。重點就在轉化了。我們普通轉化可能用switch是吧。但是源碼中可不是喲。對於-128到127之間是緩存好的數字,除此之外做了一個stirng到int的轉換,在這個int轉換中把char直接強轉成int然後對unicode做的操作,這個就挖的太深了,我們沒有必要深究了,做一些swtich轉換即可。

代碼如下:

public class StringtoInteger {
	public static void main(String[] args){
		System.out.println(method("   -  94dsad564as"));
	}
	public static int method(String s){
		int i = 0;
		int digit = 0;
		int result = 0;
		char[] cs = s.toCharArray();
		int negative = 0;//0未賦值,1負值,2正值
		while(i<cs.length){
			
			if(cs[i]=='+')//正號
			{
				if(negative != 0){
					return 0;
				}
				negative = 2;
			}else if (cs[i]=='-') {//負號
				if(negative != 0){
					return 0;
				}
				negative = 1;
			}
			else if (cs[i]>=48&&cs[i]<=57) {//數字
				digit = (int)cs[i]-48;
				result = (result<<3)+(result<<1)+digit;//*10;

			}
			i++;
		}
		return (negative==1)?-result:result;
	}
}
雖然算法不如前幾次那麼奇葩,但是還是有點意思的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章