[leetcode] String to Integer (atoi)

Implement atoi to convert a string to an integer. html

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

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


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

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

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

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


思路:題目不難,可是corner case比較多,須要仔細處理。 code

  1. 空字符:    特殊處理
  2. 空白:       最好trim一下,本身處理也行
  3. +/-符號:    當心可選的+
  4. 溢出:簡單處理能夠用long或者double存放結果最後強轉回來;或者累積算結果時提早對 max/10或者min/10比較一下來預測是否會溢出,等到溢出再比較就來不及了。

基本上都是本身處理的代碼(未整理,有點亂。。): orm

public class Solution {
	public int atoi(String str) {
		int max = 2147483647;
		int min = -2147483648;
		int result = 0;
		int len = str.length();
		int start = -1;
		boolean neg = false;
		for (int i = 0; i < len; i++) {
			char ch = str.charAt(i);
			if (ch == '+' || ch == '-' || (ch >= '0' && ch <= '9')) {
				start = i;
				break;
			} else if (ch == ' ') {

			} else {
				break;
			}
		}
		if (start == -1)
			return 0;

		if (str.charAt(start) == '-' || str.charAt(start) == '+') {
			if (str.charAt(start) == '-')
				neg = true;
			start++;
		}

		for (int i = start; i < len; i++) {
			char ch = str.charAt(i);
			char next = 0;
			if (i + 1 < len)
				next = str.charAt(i + 1);
			if (ch < '0' || ch > '9')
				break;
			result = 10 * result + (ch - '0');

			if (next >= '0' && next <= '9') {
				if (result > max / 10) {
					if (neg)
						return min;
					else
						return max;
				}

				if (result == max / 10) {
					if (neg) {
						if (next - '0' >= 8)
							return min;
						else
							return -1 * (10 * result + (next - '0'));

					} else {
						if (next - '0' >= 7)
							return max;
						else
							return 10 * result + (next - '0');
					}
				}
			}

		}
		if (neg)
			result = -result;

		return result;
	}

	public static void main(String[] args) {
		System.out.println(new Solution().atoi(" -1010023630"));
		System.out.println(new Solution().atoi(" -1010023630o4"));
		System.out.println(new Solution().atoi("    10522545459"));
		System.out.println(new Solution().atoi("   123"));
		System.out.println(new Solution().atoi("  -123"));
		System.out.println(new Solution().atoi("  +123"));
		System.out.println(new Solution().atoi("  -1234bbsf3"));
		System.out.println(new Solution().atoi("  2147483646"));
		System.out.println(new Solution().atoi("  2147483647"));
		System.out.println(new Solution().atoi("  2147483648"));
		System.out.println(new Solution().atoi("  2147483649"));
		System.out.println(new Solution()
				.atoi("  11111111111111111111111111111111111111111111111111"));

		System.out.println(new Solution().atoi(" -2147483647"));
		System.out.println(new Solution().atoi(" -2147483648"));
		System.out.println(new Solution().atoi(" -2147483649"));
		System.out.println(new Solution()
				.atoi("  -11111111111111111111111111111111111111111111111111"));
		System.out.println(new Solution().atoi("0"));
		System.out.println(new Solution().atoi("abc"));

	}

}


整理後,簡單實現: htm

public class Solution {
    public int atoi(String str) {
        int max = Integer.MAX_VALUE;
        int min = -Integer.MIN_VALUE;
        long result = 0;
        str = str.trim();
        int len = str.length();
        if (len < 1)
            return 0;
        int start = 0;
        boolean neg = false;

        if (str.charAt(start) == '-' || str.charAt(start) == '+') {
            if (str.charAt(start) == '-')
                neg = true;
            start++;
        }

        for (int i = start; i < len; i++) {
            char ch = str.charAt(i);

            if (ch < '0' || ch > '9')
                break;
            result = 10 * result + (ch - '0');
            if (!neg && result > max)
                return max;
            if (neg && -result < min)
                return min;

        }
        if (neg)
            result = -result;

        return (int) result;
    }


}





參考:

http://jane4532.blogspot.com/2013/09/string-to-integerleetcode.html

http://www.programcreek.com/2012/12/leetcode-string-to-integer-atoi/

相關文章
相關標籤/搜索