• [leetcode] 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.

     https://oj.leetcode.com/problems/string-to-integer-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.

    思路:题目不难,但是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;
        }
    
    
    }

     第二遍记录:

      用long处理溢出的情况。

      -Integer.MIN_VALUE 依然是自己本身,二进制取反加一还是原来的样子。 

    第三遍记录:

      溢出的判断不用提升到long,相乘计算之前要跟max/10判断是否溢出,否则计算完之后再考虑溢出就晚了。

      注意负数的%操作是依赖编译器的,所以要小心负数最大情况的对比。java: -5%10= -5

    public class Solution {
    
        public int atoi(String s) {
            if (s == null)
                return 0;
            s = s.trim();
            if (s.length() == 0)
                return 0;
            int start = 0;
            boolean neg = false;
            int res = 0;
            int max = Integer.MAX_VALUE;
            int min = Integer.MIN_VALUE;
    
            if (s.charAt(0) == '+' || s.charAt(0) == '-') {
                start++;
                if (s.charAt(0) == '-')
                    neg = true;
            }
            for (int i = start; i < s.length(); i++) {
                int curNum = (int) (s.charAt(i) - '0');
                if (curNum < 0 || curNum > 9)
                    break;
                if (!neg && (res > max / 10 || res == max / 10 && curNum >= max % 10))
                    return max;
    
                if (neg && (res > max / 10 || res == max / 10 && curNum >= -(min % 10)))
                    return min;
    
                res = res * 10 + curNum;
            }
    
            return neg ? -res : res;
    
        }
    
    
    }

    想想 atof()如何实现

    跟atoi类似,注意小数点的处理和小数点后面数字的累加方式是不同的。

    http://www.cnblogs.com/wb118115/archive/2012/11/08/2761730.html

    参考:

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

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

  • 相关阅读:
    利用 Makefile 写的小程序
    linux内核学习之进程管理------task_struct结构体
    智能指针
    explicit 关键字
    ant脚本编写
    FROM_UNIXTIME 格式化MYSQL时间戳函数
    Dubbo架构设计详解-转
    Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)转
    SiteMesh详解
    sitemesh使用步骤
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810677.html
Copyright © 2020-2023  润新知