码迷,mamicode.com
首页 > 其他好文 > 详细

String to Integer (atoi) -- leetcode

时间:2014-12-15 09:09:52      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:leetcode   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... click to show requirements for atoi.

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.

简言之,题目要求实现atoi功能。

在g++,诸如+-+-10, -+-+10, +-+10常量都是合法的,值分别为 10, 10, -10.

此题目中,此类写法,则会要求返回0.即只认一个+或-。


class Solution {
public:
    int atoi(const char *str) {
        while (*str == ' ') ++str;
        const bool isNeg = *str == '-' ? true : false;
        if (*str == '+' || *str == '-') ++str; // do not support +-+- etc.
        int result = 0;
        while (*str >= '0' && *str <= '9') {
                const int digit = *str - '0';
                if (!isNeg && (INT_MAX-digit)/10 < result) // it is <, not <=
                        return INT_MAX;
                else if (isNeg && (INT_MIN+digit)/10 > result) // it is >, not >=
                        return INT_MIN;
                else
                        result = result * 10 + (isNeg ? -digit : digit);

                ++str;
        }
        return result;
    }
};


如果将

                else if (isNeg && (INT_MIN+digit)/10 > result) // it is >, not >=
                        return INT_MIN;
中 > 写成 >= ,是无非被leetcode AC。


然而,

                if (!isNeg && (INT_MAX-digit)/10 < result) // it is <, not <=
                        return INT_MAX;
将< 写作 <=, 是可以被AC。但其实是不对的,看来leetcode的test case不充分。

输入串,“2147483646”, 就可以区分出用 < 和 <= 的区别了。

String to Integer (atoi) -- leetcode

标签:leetcode   atoi   面试   

原文地址:http://blog.csdn.net/elton_xiao/article/details/41927155

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!