题目描述
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
思路
注意合法性判别即可
AC代码
class Solution {
public:
int StrToInt(string str
) {
if(str
.empty()) {
return 0;
} else if((str
[0] < '0' || str
[0] > '9') && str
[0] != '+' && str
[0] != '-') {
return 0;
} else if((str
[0] == '+' || str
[0] == '-') && str
.length() == 1) {
return 0;
} else if(str
[0] > '0' && str
[0] < '9') {
for(int i
= 0; i
< str
.length(); ++i
) {
if(str
[i
] < '0' || str
[i
] > '9') {
return 0;
}
}
}
int res
= 0;
int n
= 1;
bool tag
= false;
for(int i
= str
.length() - 1; i
>= 0; --i
) {
if(str
[i
] == '-') {
tag
= true;
break;
} else if(str
[i
] == '+') {
break;
}
res
+= (str
[i
] - '0') * n
;
n
*= 10;
}
if(tag
)
res
= -res
;
return res
;
}
};
转载请注明原文地址: https://www.6miu.com/read-5033310.html