leetCode 8. String to Integer (atoi)

    題目連接:https://leetcode.com/problems/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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

    題意分析:題目很簡單,就是把string類型轉化爲一個int類型。我自己提交的答案ac之後,查看一下討論區其他人的解法,大家的思路都差不多,這道題的難度分在easy,但是通過率卻很低,很大原因就是不斷有各種test case通不過,很考驗細節(深有體會啊,一堆紅色wa~)。對於這些oj系統,還是有人說得好“難度大的題重在巧妙和思維,越是簡單的題越是重細節”。這裏的細節包括但不限於:

    1)輸入爲空

    2)邊界問題

    3)特殊符號

    含淚貼上自己AC的低質量代碼,討論區也有很多人直接用寫好的API,或者考慮邊界時候使用long類型,還有使用python的正則表達式都有。

public static int myAtoi(String str) {
		int res = 0;
		// whether res is positive or not
		boolean positive = true;
		// the num of char before digit
		int sigCount = 0;
		// ignore the space before or afer the string
		String fixStr = str.trim();
		if(!fixStr.isEmpty()) {
			int len = fixStr.length();
			int idx;
			// judge the res is positive or not, and if the char before res is not '+' nor '-', return 0
			for(idx = 0; idx < len; idx++) {
				char ch = fixStr.charAt(idx);
				if(ch >= '0' && ch <= '9') {
					// begin with digits
					break;
				} else {
					// too many sign or char isn't '+' or '-', e.g. '++-2133', ' b23351'
					if(++sigCount > 1 || (ch!='+' && ch!='-'))
						return 0;
					else if(ch == '-')
						positive = false;
				}
			}
			for(; idx < len; idx++) {
				char ch = fixStr.charAt(idx);
				if(ch >= '0' && ch <= '9') {
					// equalsTo "res*10+(ch-'0') > Integer.MAX_VALUE", which is overflow
					if(positive && res > (Integer.MAX_VALUE - (ch-'0'))/10)
						return Integer.MAX_VALUE;
					// equalsTo "-(res*10+(ch-'0')) < Integer.MIN_VALUE", which is overflow
					else if(!positive && res > -((Integer.MIN_VALUE + (ch-'0'))/10))
						return Integer.MIN_VALUE;
					else 
						res = res*10 + (ch - '0');
				} else
					// if the test case is '233f54' for example, output will be '233'
					break;
			}
		}
		return positive?res:-res;
	}


發佈了56 篇原創文章 · 獲贊 27 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章