剑指 Offer 67 把字符串转换成整数

写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。

标签:剑指 Offer发布于:编辑于:浏览量:1490

概述

https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/

https://leetcode.com/problems/string-to-integer-atoi/

有一道让你判断字符串是否是合法数字的题目跟这个很像。

解法

实现的时候要注意,INT_MIN 的绝对值要比 INT_MAX 多一,这导致其不能用 int 来存。

另外 while 循环那里如果发现已经超出 INT_MAX + 1,立刻返回 INT_MAX + 1 就好。

还有就是下面的 INT_MAX 因为后面有 + 1,所以必须将其转换到范围更大的类型。

class Solution {
public:
    int myAtoi(string s) {
        bool positive = true;
        int i = 0;
        while (s[i] == ' ') i ++;
        if (s[i] == '+') {
            i ++;
        } else if (s[i] == '-') {
            i ++;
            positive = false;
        }
        long n = 0;
        while (isdigit(s[i])) {
            n *= 10;
            if (n >= long(INT_MAX) + 1) {
                n = long(INT_MAX) + 1;
                break;
            }
            n += s[i] - '0';
            i ++;
        }
        if (positive) {
            return min(n, long(INT_MAX));
        } else {
            if (n >= long(INT_MAX) + 1) {
                return INT_MIN;
            } else {
                return - int(n);
            }
        }
    }
};