码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] [leetcode] String to Integer (atoi)

时间:2014-06-27 12:08:39      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

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.

 

思路:题目不难,但是corner case比较多,需要仔细处理。

  1. 空字符:    特殊处理
  2. 空白:       最好trim一下,自己处理也行
  3. +/-符号:    小心可选的+
  4. 溢出:简单处理可以用long或者double存放结果最后强转回来;或者累积算结果时提前对 max/10或者min/10比较一下来预测是否会溢出,等到溢出再比较就来不及了。

基本上都是自己处理的代码(未整理,有点乱。。):

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"));

	}

}

 

整理后,简单实现:

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/

 

[leetcode] [leetcode] String to Integer (atoi),布布扣,bubuko.com

[leetcode] [leetcode] String to Integer (atoi)

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!