Practice39:
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
S1
牛客解题之一
主要边界值确定要细想
class Solution {
public:
int StrToInt(string str) {
const int len = str.length();
if(len==0)return 0;
int i=0;
while(i<len&&str[i]==' '){
++i;
}
if(i==len)return 0;
if(!isdigit(str[i])&&str[i]!='+'&&str[i]!='-')return 0;
bool neg = str[i]=='-'?true:false;
i = isdigit(str[i])?i:++i;
long long ans = 0L;
while(i<len&&isdigit(str[i])){
ans = ans*10+str[i++]-'0';
if(!neg&&ans>INT_MAX){
ans = INT_MAX;
break;
}
if(neg&&ans>1L+INT_MAX){
ans = INT_MAX+1L;
break;
}
}
if(i!=len)return 0;
return !neg?ans:-ans;
}
};
博客围绕Practice39展开,要求在不使用库函数的情况下将字符串转换成整数,若数值为0或字符串不合法则返回0。解题时需仔细确定主要边界值,还提及牛客解题的一种思路。

1062

被折叠的 条评论
为什么被折叠?



