8. String to Integer (atoi)

Description:

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.

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.

Solutions:

Approach 1: Use long to handle the overflow

We need to deal with 4 issues[[1]]:

  1. trim leading white spaces
  2. number sign
  3. overflow
  4. invalid input
    [1]:https://discuss.leetcode.com/topic/2666/my-simple-solution?page=1

The 1st problem can be handled in 2 ways:
1.use trim() method of String object or 2. use a pointer to skip all the leading spaces and end up at the first non-whitespace character

The 2nd problem is easy to solve. We just need to see if the first non-whitespace character is '+' or '-'.

The 3rd problem can be handled by using a long variable, once we find the overflow happens, we break the loop and return the max_int or min_int.

The 4th problem is easy, too. Once we meet the non-digit character, we just stop our calculation process.

Here is the solution:

public class Solution {
    public int myAtoi(String str) {
        String s = str.trim();
        if (s.length() == 0 || s == null) return 0;
        boolean positive = true;
        int i = 0;
        if (s.charAt(0) == '-') {
            positive = false;
            i++;
        } else if (s.charAt(0) == '+') {
            i++;
        }
        
        long res = 0;
        while (i < s.length() && (s.charAt(i) >= '0' && s.charAt(i) <= '9')) {
            res = res*10 + s.charAt(i) - '0';
            i++;
            System.out.println("---" + i);
            // Note: you cannot use res > int_max+1
            // becuase int_max+1 will overflow to be int_min
            // why we use res-1 > int_max but not res > int
            // is because we need to handle both int_max and int_min
            if (res-1 > Integer.MAX_VALUE) break;
        }
        
        if (positive) {
            if (res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            return (int)res;
        } else {
            if (res-1 > Integer.MAX_VALUE) return Integer.MIN_VALUE;
            return ((int)res)*(-1);
        }
    }
}

Approach 2: Use int to handle the overflow

In Approach 1, we check if the overflow happens after each calculation. However, we can "predict" if the overflow will happen before calculation.
As in Approach 1, the calculation process is res = res*10 + s.charAt(i) and the res is always positive through the process. However, when we are going to "add" the next digit character to res, we can check if res is going to overflow by checking:

res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)

Explanation:

  • If res > Integer.MAX_VALUE/10, this will cause res*10 > Integer.MAX_VALUE in the next calculation, so if res > Integer.MAX_VALUE/10, the overflow must happen.
  • If res == Integer.MAX_VALUE/10, the overflow may not necessarily happen because if the next digit character is 7 or even small. res*10 + 7 is still can be presented by an int variable. But if the next digit character is greater than 7, it only can be 8 or 9. Then we should take the number sign into consideration. However, if we think it over carefully:
  • if the number is positive: whether the next is 8 or 9, res overflows, so we should return Integer.MAX_VALUE immediately.
  • if the number is negative: if the next is 8, res does not overflow but would be Integer.MAX_VALUE, at this point we don't have to see if the next character is digit and "add" it to res because the overflow will happen so we should return Integer.MIN_VALUE; if the next is 9, res overflows and we should return Integer.MIN_VALUE. As a result, whether it is 8 or 9, we should return Integer.MIN_VALUE.

So only res == Integer.MAX_VALUE/10 is not enough to say that overflow will happen but res == Integer.MAX_VALUE/10 && s.charAt(i- > '7' will handle it.

The solution is:

public class Solution {
    public int myAtoi(String str) {
        if (str == null || str.isEmpty()) return 0;
        int sign = 1, base = 0, i = 0, n = str.length();
        while (i < n && s.charAt(i) == ' ') i++;
        if (i < n && (str.charAt(i) == '-' || str.charAt(i) == '+'))
            sign = str.charAt(i++) == '-' ? -1 : 1;
        while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            res = 10 * res + (str.charAt(i++) - '0');
        }
        return res * sign;
    }
}

Note: every time we call s.charAt(i) we should check if i goes out of the boundary.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,938评论 0 0
  • 尼玛,我要被这道题的题目搞死了... 2016/10/12编程语言是 Java,代码托管在我的...
    秋名山菜车手阅读 3,882评论 2 4
  • “只是因为在人群中多看了你一眼,再也没能忘掉你容颜,梦想着偶然能有一天再相见,从此我开始孤单思念,想你时你在天边,...
    风衣雨剑阅读 1,566评论 0 1
  • 她是我们班的传奇,虽然年龄是我们班最小的,但是成绩一直是我们班的第一,每次都拉第二名二三十分,霸主地位毋庸置...
    一席江月阅读 1,163评论 0 0
  • 文/步月 1 朋友给我发微信,隔着屏幕都可以想像她一脸的无奈:“月,你说奶奶年纪都这么大了,怎么看事还没我通透?”...
    步月儿阅读 10,331评论 13 18