[LeetCode] 8. String to Integer (atoi)

陪她去流浪 桃子 2014年10月26日 阅读次数:1846

原文:String to Integer (atoi)

描述:把字符串转换成整数(实现 atoi)。

思路:逐字符乘 10 累加即可。

提示:

  1. 应忽略所有前导空白字符;
  2. 可能有符号标识位;
  3. 尽可能多地读取数字位;
  4. 数字位后面可能有无效字符,应全部忽略,不影响此函数的行为;
  5. 如果字符串无法执行转换,应返回 0;
  6. 如果转换超出范围,应返回对应的最大值 INT_MAX / 最小值 INT_MIN;

代码:

class Solution {
public:
    int myAtoi(string str) {
        bool plus = true;
        size_t i = 0;
        long long tmp = 0;

        // skips whitespaces
        while(str[i] == ' ' || str[i] == '\t')
            i++;

        // takes sign character
        if(str[i]=='+' || str[i]=='-'){
            plus = str[i]=='+';
            i++;
        }

        // reads the integer
        while(str[i]>='0' && str[i]<='9'){
            tmp *= 10;
            tmp += str[i]-'0';
            i++;
            if(plus){
                if(tmp > (long long)INT_MAX){
                    return INT_MAX;
                }
            }
            else{
                if(tmp > (long long)INT_MAX+1){
                    return INT_MIN;
                }
            }
        }

        return plus ? int(tmp) : -int(tmp);
    }
};

这篇文章的内容已被作者标记为“过时”/“需要更新”/“不具参考意义”。

标签:LeetCode