题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
示例1
输入
+2147483647 1a33
输出
2147483647 0
思路:设置一个check函数,判断该字符是否为数字;对字符串的首个字符进行判断,若为‘+’‘-’,则设定好正负号,其后字符进行判断,若不是数字则直接返回0,若是数字,则res = res*10 + ch - '0'
代码:
class Solution {
public:
inline bool isNum(char ch) {
if(ch >= '0' && ch <= '9')
return true;
return false;
}
int StrToInt(string str) {
if(str.empty())
return 0;
int len = str.size();
int res = 0;
int pos = 1;
for(int i = 0; i < len; ++i) {
if(i == 0 && (str[i] == '+' || str[i] == '-')) {
if(str[i] == '-') {
pos = -1;
}
continue;
}
if(isNum(str[i])) {
res = res*10 + str[i] - '0';
}else {
return 0;
}
}
return pos * res;
}
};
方案二:
应考虑到多种非法情况,例如:空指针(NULL)、空字符串(只有一个‘\0’)、数值越界、非法字符串、首字符为‘+’‘-’、返回0时表示非法情况还是表示数值为0(需要设置全局变量作为标志位)
代码如下:
class Solution {
public:
enum state{kValid = 0, kInvalid};
int gState = kValid;
int StrToInt(string str) {
gState = kInvalid;
int num = 0;
const char* cstr = str.c_str();
if(cstr != NULL && *cstr != '\0') {
int minus = 1;
if(*cstr == '-') {
minus = -1;
++cstr;
} else if(*cstr == '+'){
++cstr;
}
while(*cstr != '\0') {
if(*cstr > '0' && *cstr < '9') {
gState = kValid;
num = num*10 + *cstr - '0';
++cstr;
if((minus>0 && num > 0x7FFFFFFF) || (minus<0 && num > 0x80000000)) {
gState = kInvalid;
num = 0;
break;
}
} else {
gState = kInvalid;
num = 0;
break;
}
}
if(gState == kValid)
num = num * minus;
}
return (int)num;
}
};
方案三(二刷版)
class Solution {
public:
enum state{Valid = 0, Invalid = 1};
int gstate = Invalid;
int StrToInt(string str) {
int len = str.size();
if(len == 0) return 0; //return 0 and Invalid;
long long res = 0;
int negative = 1;
for(int i = 0; i < len; ++i) {
if(i == 0 && (str[i] == '+' || str[i] == '-')) {
if(str[i] == '-') {
negative = -1;
}
continue;
}
if(str[i] >= '0' && str[i] <= '9') {
res = res * 10 + negative * (str[i] - '0');
if(res > INT_MAX || res < INT_MIN) {
return 0; //return 0 and out of limit Invalid;
}
} else {
return 0; //return 0 and Invalid;
}
}
gstate = Valid;
return int(res);
}
};