试题请參见: 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. Suricata, to 10Gbps and beyond(X86架构)

    Introduction Since the beginning of July 2012, OISF team is able to access to a server where one int ...

  2. Decorator Pattern(装饰模式)

    装饰模式:动态的给一个对象添加一些额外的职责.当然我们也可以通过继承来实现类似的功能,但是随着子类的增多,各种子类的组合会造成子类的急剧膨胀. Requirement: 假设客户有一个要求,需要打一个 ...

  3. Oracle存储包存储及案例

    Package左侧文件: create or replace package S02_ZFRZPT_YS_MID is procedure start_cal(strgranularity in va ...

  4. java URI 与URL问题

    File类存在两个看起来很相似的方法toURI()和toURL(),这两个方法都是将文件转换成一个链接,可以网络访问.只是URI和URL的应用范围不同,URI来的更广. 那么为什么要使用toURI() ...

  5. ClassLoader简单介绍

    要理解ClassLoader,我们可以通过what.how两个方面来解释 一.what:什么事ClassLoader? 1.ClassLoader可以是将class文件加载到JVM方法区. 2.Cla ...

  6. mac下面xcode+ndk7配置cocos2dx & box2d的跨ios和android平台的游戏教程

    这篇教程是介绍如何使用cocos2d-x和box2d来制作一个demo,且此demo能同时运行于ios和android平台.在继续阅读之前,建议您先阅读上一篇教程. 首先,按照上一篇教程,搭建好mac ...

  7. JS拖动DIV布局

    方法一: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...

  8. FPGA知识大梳理(一)对FPGA行业的一点感言

    今天想开始把这FPGA行业的知识点做一个大整理,从个人感想,到语法,到器件基础,难点攻克,到项目应用.把自己这几年接触到的知识做一个全面的回顾,看看自己这几年走过的路. 人生无常,几年的跌跌撞撞勉强算 ...

  9. 高级UNIX环境编程10 信号

    信号是软件中断,提供一种处理异步事件的方法 <signal.h> sigaction()

  10. 删除 Windows Azure 网站上的标准服务器头

    编辑人员注释: 本文章由 Windows Azure 网站团队的项目经理 Erez Benari 撰写. 请求和响应中包含的 HTTP 头是Web 服务器和浏览器之间的 HTTP 通信过程的一部分.例 ...