[LeetCode] 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.

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) orINT_MIN (-2147483648) is returned.

  • 实现代码
/*************************************************************
    *  @Author   : 楚兴
    *  @Date     : 2015/2/7 14:47
    *  @Status   : Accepted
    *  @Runtime  : 15 ms
*************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    int atoi(const char *str) {
        long long num = 0;
        while (*str == ' ')  //去掉空格
        {
            str++;
        }

        bool flag = false;  //获取可选的正负号
        if (*str == '+')
        {
            str++;
        }
        else if (*str == '-')
        {
            flag = true;
            str++;
        }

        //如果第一个序列的非空格字符不是有效地数字字符,则返回0
        if (*str < '0' || *str > '9')
        {
            return 0;
        }

        while(*str)
        {
            if (*str >= '0' && *str <= '9')
            {
                num = num * 10 + *str - '0';
                str++;
                if (num > INT_MAX)
                {
                    if (!flag)
                    {
                        return INT_MAX;  //INT_MAX = 2147483647
                    }
                    else
                    {
                        return INT_MIN;  //INT_MIN = -2147483648
                    }
                }
            }
            else
            {
                break;
            }
        }

        if (flag)  //加上负号
        {
            num = -num;
        }

        return num;
    }
};

应该特别注意越界的情况,输入数据甚至可能越long long类型的界。

时间: 2024-09-11 17:34:54

[LeetCode] String to Integer (atoi)的相关文章

[LeetCode]8. 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 probl

LeetCode 8 String to Integer (atoi)(转换到整型)

翻译 实现"atoi"将字符串转换成整型数. 提示:仔细考虑所有可能的输入.如你想要挑战,请不要参阅下面并问问自己都有哪些可能的输入请看. 说明:模糊的指定(没有给定的输入规格)就是为了这个问题.你负责收集所有可能的输入. atoi的要求: 函数首先放弃尽可能多的空字符直到找到一个非空白字符.然后从这个字符开始,带上可选的初始加/减字符,其后还可能跟着越多越好的数字,并将它们解释成一个数值. 这个字符串可能在这些数字之后包含一些附加的字符,它们可以可以被忽略,并对函数的行为没有影响.

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 spe

LeetCode 7 Reverse Integer(翻转整数)

翻译 翻转一个整型数 例1:x = 123, 返回 321 例2:x = -123, 返回 -321 原文 Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Have you thought about this? (来自LeetCode官网) Here are some good questions to ask before coding. Bonus poi

String to 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). Y

leetcode 7 Reverse Integer

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers. Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought throu

leetcode难度及面试频率

转载自:LeetCode Question Difficulty Distribution               1 Two Sum 2 5 array sort         set Two Pointers 2 Add Two Numbers 3 4 linked list Two Pointers           Math 3 Longest Substring Without Repeating Characters 3 2 string Two Pointers      

LeetCode总结【转】

转自:http://blog.csdn.net/lanxu_yy/article/details/17848219 版权声明:本文为博主原创文章,未经博主允许不得转载. 最近完成了www.leetcode.com的online judge中151道算法题目.除各个题目有特殊巧妙的解法以外,大部分题目都是经典的算法或者数据结构,因此做了如下小结,具体的解题思路可以搜索我的博客:LeetCode题解 题目 算法 数据结构 注意事项 Clone Graph BFS 哈希表 Word Ladder II

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能