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 problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

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.

我的思路

此题主要要考虑题目提示的一些特殊情况:

  1. 字符开始是空格时,将其忽略掉;
  2. 当首个非空格字符出现时,如果是 '0''9' 或者 '+''-' 时,开始记录并转化为数字。否则直接返回 0,例如,输入为:" a2",输出为 0
  3. 从第二个非空格字符开始,如果遇到不是 '0''9' 这些字符,则返回当前记录到的数字。例如,输入为:"+-2",输出为 0
  4. 如果检测到字符串转成整型会溢出的话,那么直接返回 INT_MAX 或者 INT_MIN

将字符串转成数字的算法:res = res * 10 + sign * (str[i] - 48); ,其中,sign 代表数字是正数还是负数。

由于字符 '0' 的 ASCII 码为 48,所以当 str[i] 为字符 '0''9' 之间时,str[i] - 48 这句代码即可将该字符转成对应的数字。

代码

int myAtoi(char* str) {
    const int maxLen = 10;
    int len = strlen(str);
    int numCnt = 0, sign = 1;
    int i = 0, j = 0;
    int flag = 0;
    int res = 0;

    // Discard non-numerical characters of str.
    // ASCII: '0' => 48, '9' => 57
    while(str[i] != '\0') {
        if(((str[i] >= '0') && (str[i] <= '9')) 
            || (((str[i] == '-') || (str[i] == '+')) && (flag == 0))) {
            if(str[i] == '-') {
                sign = -1;
                i++;
                flag = 1;
                continue;
            }
            if(str[i] == '+') {
                sign = 1;
                i++;
                flag = 1;
                continue;
            }

            if(!((numCnt == 0) && (str[i] == '0'))) {
                numCnt++;
                if(numCnt == maxLen) {
                    if(sign == 1) {
                        if((res > INT_MAX / 10) ||
                            (res == INT_MAX / 10) 
                            && (sign * (str[i] - 48) > INT_MAX % 10)) {
                            // Overflow
                            return INT_MAX;
                        }
                    }
                    if(sign == -1) {
                        if((res < INT_MIN / 10) ||
                            (res == INT_MIN / 10) 
                            && (sign * (str[i] - 48) < INT_MIN % 10)) {
                            // Overflow
                            return INT_MIN;
                        }
                    }
                }
                if(numCnt > maxLen) {
                    // Overflow
                    if(sign == 1) {
                        return INT_MAX;
                    }

                    if(sign == -1) {
                        return INT_MIN;
                    }
                }
                res = res * 10 + sign * (str[i] - 48);
            }
        }
        else {
            if((numCnt > 0) || (flag == 1)
                || ((numCnt == 0) && (str[i] != ' '))) {
                break;
            }
        }

        i++;
    }

    return res;
}

优化代码

下面优化的代码来源于 leetcode.com 上其他人的 submissions。

上述代码稍显啰嗦,下面对代码优化一下。

首先,对于第1点,字符串开始是空格的情况,可以用下述代码将其排除掉。利用指针运算直接把指针指向首个非空字符。

while (*str == ' ')
    str++;

然后就是对正负符号的判断,虽然下面的代码跟优化前的代码都是通过变量 sign 来表示正负数,但是下面的代码要更简洁明了。

if(*str == '+' || *str == '-') {
    if (*str == '-')
        sign = -1;
    str++;
}

判断完符号之后,接着就是将字符转化成数字,并且判断数字是否溢出。完整的代码如下:

int myAtoi(char* str) {
    int val = 0;
    int sign = 1;

    while (*str == ' ')
        str++;
    if(*str == '+' || *str == '-') {
        if (*str == '-')
            sign = -1;
        str++;
    }
    //printf("\n VAL %d\n", val);
    while (*str >= '0' && *str <= '9'){
        //printf("\n 1. VAL %d\n", val);
        if ((val > INT_MAX / 10) || ((val == INT_MAX / 10) && (*str - '0' > 7))){
            //printf("\n Reached here Val %d, *str %c\n", val, *str);
            if (sign == 1)
                return INT_MAX;
            else if (sign == -1)
                return INT_MIN;
        }
        val = (val * 10) + (*str - '0');
        str++;
    }

    return val * sign;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值