试题请參见: https://oj.leetcode.com/problems/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.

spoilers alert...

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.

解题思路

这道题目还真是艰辛~ 看起来非常基础, 但是有些Case还真是暗藏玄机.

主要问题还是推断是否越界. 
我的做法是, 记录n = n * 10 + currentDigit运算前n的值. 若运算后n / 10和之前记录下来的值相等, 则还未越界.

源码

class Solution {
public:
    int atoi(const char *str) {
        int n = 0;
        bool isPositive = true;
        size_t i = 0;
        
        // Ignore Spaces
        for ( ; str[i] == ' ' && str[i] != 0; ++ i ) { }
        
        // Process Sign Bit
        if ( str[i] == '+' || str[i] == '-' ) {
            isPositive = (str[i] == '+');
            ++ i;
        }         // Convert to Integer
        for ( ; isDigit(str[i]) && str[i] != 0; ++ i ) {
            char digit = str[i] - '0';
            int previousResult = n;
            n = n * 10 + digit;             // If it's Overflow
            if ( n / 10 != previousResult ) {
                if ( isPositive ) {
                    return INT_MAX;
                } else {
                    return INT_MIN;
                }
            }
        }
        
        return ( isPositive ? n : -n );
    }
private:
    bool isDigit(char digit) {
        return (digit >= '0' && digit <= '9');
    }
};

LeetCodeOJ. String to Integer (atoi)的更多相关文章

  1. 【leetcode】String to Integer (atoi)

    String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...

  2. No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  3. leetcode第八题 String to Integer (atoi) (java)

    String to Integer (atoi) time=272ms   accepted 需考虑各种可能出现的情况 public class Solution { public int atoi( ...

  4. leetcode day6 -- String to Integer (atoi) &amp;&amp; Best Time to Buy and Sell Stock I II III

    1.  String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully con ...

  5. String to Integer (atoi) - 字符串转为整形,atoi 函数(Java )

    String to Integer (atoi) Implement atoi to convert a string to an integer. [函数说明]atoi() 函数会扫描 str 字符 ...

  6. Kotlin实现LeetCode算法题之String to Integer (atoi)

    题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 class ...

  7. LeetCode--No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  8. leetcode-algorithms-8 String to Integer (atoi)

    leetcode-algorithms-8 String to Integer (atoi) Implement atoi which converts a string to an integer. ...

  9. LeetCode: String to Integer (atoi) 解题报告

    String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...

随机推荐

  1. libcurl的使用问题“Expect100-continue”

    最近在做团购酒店APP分享到qzone功能,使用libcurl访问qzone的分享cgi接口,酒店分享信息以POST方式传输,在测试的时候发现分享接口平均有2s的延迟,这延迟也太大了吧,于是乎问了空间 ...

  2. [置顶] P2P网贷对推动社会发展的影响

    P2P网贷对推动社会发展的影响 1 真正的支持了实体经济,一般借款人就在几万或者50万以下 2 关照小微经济,新型行业.一般小微经济的创新更高,对社会的发展最大化. 3盘活存量 放到银行.保险.国债一 ...

  3. html5 中的SVG 和canvas

    想到昨天看资料的时候,发现html5 中的SVG 和canvas 都可以表示图形,那它们到底有哪些区别呢?该如何正确的使用它们呢? 1.SVG:可缩放矢量图形,(Scalable Vector Gra ...

  4. jQuery对DOM的操作

    "jQuery中非常重要的部分,就是对DOM的操作!" "jQuery中非常重要的部分,就是对DOM的操作!" "jQuery中非常重要的部分,就是对 ...

  5. UVA 674 Coin Change(dp)

    UVA 674  Coin Change  解题报告 题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=87730#problem/ ...

  6. hdoj 1013

    比较坑的一道题...直接做肯定WA http://acm.hdu.edu.cn/showproblem.php?pid=1013 #include<iostream> #include&l ...

  7. WebHdfs

    https://github.com/ihrwein/webhdfs https://tiborbenke.blogs.balabit.com/2013/11/the-syslog-ng-in-the ...

  8. qt qml 利用xmlhttprequest 调用有赞api

    最近朋友在有赞商城上面开了一个店铺,因为有实体店,一般卖商品后送货上门,但是打票时候老是人工用world文档人工复制黏贴订单打印小票, 所以就找我帮忙做一个软件专门打印小票的,就研究起来调用有赞第三方 ...

  9. 教你怎么用Mono Cecil - 动态注入 (注意代码的注释)

    原文 教你怎么用Mono Cecil - 动态注入 (注意代码的注释) 使用 Mono Cecil 进行反编译:using Mono.Cecil; using Mono.Cecil.Cil; //.. ...

  10. Windows Phone 8初学者开发—第11部分:设置SounBoard应用程序

    原文 Windows Phone 8初学者开发—第11部分:设置SounBoard应用程序 原文地址: http://channel9.msdn.com/Series/Windows-Phone-8- ...