试题请參见: 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. DOM Traversal Example | Documentation | Qt Project

    DOM Traversal Example | Documentation | Qt Project DOM Traversal Example

  2. Node安装及搭建简单服务器

    注:本文安装系统为mac,windows及其他系统下载对应安装包 ,mac下载后的安装包为apk文件,windows为msi文件. 安装 1.在网上下载node安装包,官方网站2.双击下载文件,按步骤 ...

  3. android中使用surfaceview+MediaPlayer播放视频

    Android中播放视频主要有两种方式: 使用其自带的播放器.指定Action为ACTION_VIEW,Data为Uri,Type为其MIME类型 使用android自带的VideoView,这种方法 ...

  4. Flex中神奇的快速辅助 Ctrl+1

    Adobe Flash Builder 中的快速辅助功能提供基于上下文的辅助,有助于您快速执行任务.通过快速辅助,可以在适用于当前代码段的操作列表中选择一个操作. 要调用快速辅助,请在编辑器的上下文菜 ...

  5. What day is that day?(快速幂,打表找周期,或者求通项公式)

    有些题怎么都解不出来,这时候可以打表,找规律,求通项公式等,这些方法让人拍手叫绝,真不错…… Description It's Saturday today, what day is it after ...

  6. BZOJ 4143 The Lawyer

           这道题看起来很吓人,但事实上看懂后会发现,其根本没有任何技术含量,做这道题其实要考虑的就是每天最早结束的一场的结束时间以及最晚开始的一场的开始时间,如果结束时间早于开始时间,那么OK就这 ...

  7. mysql存储过程详解[转]

    1.      存储过程简介   我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储 ...

  8. hdu 2814 快速求欧拉函数

    /** 大意: 求[a,b] 之间 phi(a) + phi(a+1)...+ phi(b): 思路: 快速求欧拉函数 **/ #include <iostream> #include & ...

  9. linux中grep的用法

    http://www.9usb.net/200902/linux-grep.html http://blog.51yip.com/linux/1008.html http://blog.csdn.ne ...

  10. ios7状态栏属性的设置

    /* 状态栏的管理: 1> iOS7之前:UIApplication进行管理 2> iOS7开始:交给对应的控制器去管理 */ // 设置状态栏的样式 - (UIStatusBarStyl ...