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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容

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