LeetCode String to Integer (atoi)

来源:互联网 发布:足球数据直播 编辑:程序博客网 时间:2024/06/07 16:20

问题网址:https://leetcode.com/problems/string-to-integer-atoi/description/

问题描述:
实现atoi将字符串转换为整数。

提示:仔细考虑所有可能的输入案例。 如果你想要一个挑战,请不要看下面,问自己什么是可能的输入案例。

注意:这个问题的含义是模糊的(即没有给定的输入规范)。 您有责任预先收集所有的输入要求。

更新(2015-02-10):
C ++函数的签名已经更新了。 如果您仍然看到您的函数签名接受一个const char *参数,请单击重新加载按钮重置您的代码定义。

对atoi的要求:
该函数首先丢弃尽可能多的空白字符,直到找到第一个非空白字符。 然后,从这个字符开始,采用一个可选的初始加号或减号,后面跟随尽可能多的数字,并将其解释为一个数字值。

该字符串可以包含附加字符后面的那些形成整数的数字,这些字符被忽略,对这个函数的行为没有影响。

如果str中的第一个非空白字符序列不是有效整数,或者由于str为空或只包含空格字符而不存在这样的序列,则不执行转换。

如果不能执行有效的转换,则返回零值。 如果正确值超出了可表示值的范围,则返回INT_MAX(2147483647)或INT_MIN(-2147483648)。

以下是几种实现

int atoi(const char *str) {    int sign = 1, base = 0, i = 0;    while (str[i] == ' ') { i++; }    if (str[i] == '-' || str[i] == '+') {        sign = 1 - 2 * (str[i++] == '-');     }    while (str[i] >= '0' && str[i] <= '9') {        if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {            if (sign == 1) return INT_MAX;            else return INT_MIN;        }        base  = 10 * base + (str[i++] - '0');    }    return base * sign;}

下面给出更快的,也是更简洁的一种处理。

class Solution {public:    int reverse(int x) {        long long res = 0;        while(x) {            res = res*10 + x%10;            x /= 10;        }        return (res<INT_MIN || res>INT_MAX) ? 0 : res;    }};
int myAtoi(string str) {    long result = 0;    int indicator = 1;    for(int i = 0; i<str.size();)    {        i = str.find_first_not_of(' ');        if(str[i] == '-' || str[i] == '+')            indicator = (str[i++] == '-')? -1 : 1;        while('0'<= str[i] && str[i] <= '9')         {            result = result*10 + (str[i++]-'0');            if(result*indicator >= INT_MAX) return INT_MAX;            if(result*indicator <= INT_MIN) return INT_MIN;                        }        return result*indicator;    }}