面试题67:把字符串转换成整数
文章目录
题目
写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。
考点
模拟
LeetCode版本
class Solution {
public:
int getNum(int &idx, string str, int flag){
long long res = 0;
while(str[idx] >='0' && str[idx] <= '9'){
res = res*10+ flag*(str[idx] - '0');
idx++;
if(res > INT_MAX) return INT_MAX;
if(res < INT_MIN) return INT_MIN;
}
return res;
}
int strToInt(string str) {
if(str.empty())return 0;
int flag = 1;
int idx = 0;
int res ;
while(str[idx] == ' '){
idx++;
}
if(str[idx] == '-'){
flag = -1;
res = getNum(++idx,str,flag);
}
else if(str[idx] == '+'){
res = getNum(++idx,str,flag);
}
else{
res = getNum(idx,str,flag);
}
return res;
}
};