首先想到C++中的atoi函数,函数为int atoi(const char* a),此处函数输入要求是const char*类型。string转换为const char*可以使用str.c_str()得到一个int类型。
需要注意的特殊情况有:
- 整数的范围,如果超过这个范围则输出上下界即可。
- 字符串前面有空格,并不是一开始就是数字
常见的数据类型的范围。其中编程的时候忘记了可以写成INT_MAX,INT_MIN
unsigned int 0~4294967295
int -2147483648~2147483647
unsigned long 0~4294967295
long -2147483648~2147483647
long long的最大值:9223372036854775807
long long的最小值:-9223372036854775808
unsigned long long的最大值:1844674407370955161
__int64的最大值:9223372036854775807
__int64的最小值:-9223372036854775808
unsigned __int64的最大值:18446744073709551615
class Solution {
public:
int myAtoi(string str) {
long result = 0;
int indicator = 1;
int 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;
}
};