zoukankan      html  css  js  c++  java
  • 8. String to Integer (atoi)

    
    
    Implement atoi which converts a string to an integer.
    
    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.
    
    Note:
    
    Only the space character ' ' is considered as whitespace character.
    Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
    Example 1:
    
    Input: "42"
    Output: 42
    Example 2:
    
    Input: "   -42"
    Output: -42
    Explanation: The first non-whitespace character is '-', which is the minus sign.
                 Then take as many numerical digits as possible, which gets 42.
    Example 3:
    
    Input: "4193 with words"
    Output: 4193
    Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
    Example 4:
    
    Input: "words and 987"
    Output: 0
    Explanation: The first non-whitespace character is 'w', which is not a numerical 
                 digit or a +/- sign. Therefore no valid conversion could be performed.
    Example 5:
    
    Input: "-91283472332"
    Output: -2147483648
    Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
                 Thefore INT_MIN (−231) is returned.
    

      

    这道题还是对于Integer的处理,在Reverse Integer这道题中我有提到,这种题的考察重点并不在于问题本身,而是要注意corner case的处理,整数一般有两点,一个是正负符号问题,另一个是整数越界问题。思路比较简单,就是先去掉多余的空格字符,然后读符号(注意正负号都有可能,也有可能没有符号),接下来按顺序读数字,结束条件有三种情况:(1)异常字符出现(按照C语言的标准是把异常字符起的后面全部截去,保留前面的部分作为结果);(2)数字越界(返回最接近的整数);(3)字符串结束。代码如下:

    public int myAtoi(String str) {
            
            if (str == null) {
                return 0;
            }
            str = str.trim();
            if (str.length() == 0) {
                return 0;
            }
            
            boolean isNeg = false;       
            int i = 0;
            if (str.charAt(0) == '-') {
                i++;
                isNeg =  !isNeg;
            } else if (str.charAt(0) == '+') {
                i++;
            }
            int ans = 0;
            while (i < str.length()) {
                if (str.charAt(i) < '0'|| str.charAt(i) > '9') {
                    break;
                }
                int digit =  (int)(str.charAt(i) - '0');
                if (isNeg && ans > -((Integer.MIN_VALUE + digit) / 10)) {
                    return Integer.MIN_VALUE;
                }
                if (!isNeg && ans > ((Integer.MAX_VALUE - digit) / 10)) {
                    return Integer.MAX_VALUE;
                }
                ans = ans * 10 + digit;
                i++;
            }
            if (ans == 0) {
                return 0;
            }else if (isNeg) {
                return -ans;
            } else {
                return ans;
            }
        }
    
    ((Integer.MAX_VALUE - digit) / 10)) 双括号啊兄弟!

    we should pay more attention to the corner case. One is that is the result positive or negative? the other is when is the correct value out of the range of representable values?

    Besides, according to the question, we should trim white space in the String, and disern the additional characters in the string.

  • 相关阅读:
    关于JAVA的线程问题
    Java 对JTextField添加回车响应
    Failed to install *.apk on device 'emulator-5554': timeout .
    静态属性
    类与对象的实例属性

    面向对象2
    面向对象设计
    re模块,主要用来查询
    xml对标签操作,
  • 原文地址:https://www.cnblogs.com/apanda009/p/7344207.html
Copyright © 2011-2022 走看看