8. String to Integer (atoi)

字符串处理的问题,有几个点要注意。

string 里的 find(), find_first_of(), find_first_not_of() 如果没找到,返回string::nops。

C++ reference 中 npos 是这样描述的: This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.

因此,做题时最好将 size_t 转换为 int, 直接 int pos=str.find() ,如果找不到就是-1了。同样的,很多STL库里的函数,如常用的 size(),返回值都是 size_t,最好转换成 int ,否则对其进行运算时容易出现越界(int 与 unsigned_int 运算 int 会强制转换为 unsigned_int)。

int 32位,范围是-2^31~2^31-1。 负数用补码形式保存,补码=反码+1。本题每次加上新的位时要判断是否越界,否则正数会加成负数。

class Solution {
public:
    int myAtoi(string str) {
        int i=str.find_first_not_of(' ');
        int indicator=1;
        if (i<str.size() && (str[i]=='-'||str[i]=='+')){
            if (str[i++]=='-') indicator=-1;
        }
        long long num=0;
        while (i<str.size() && isdigit(str[i])){
            num = 10*num+(str[i++]-'0');
            if (indicator*num>=INT_MAX) return INT_MAX;
            if (indicator*num<=INT_MIN) return INT_MIN;  
        }
        return indicator*num;
    }
};

 

posted @ 2018-06-08 14:44  約束の空  阅读(101)  评论(0)    收藏  举报