题解 | #把字符串转换成整数(atoi)#
把字符串转换成整数(atoi)
http://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
int StrToInt(string s) {
// write code here
int n=0;
while(s[n]==' '){
n++;
}
long long sum=0;
bool op=false;
if(s[n]=='-')
{
op=true;
n++;
}else if(s[n]=='+'){
n++;
}
while(s[n]<='9'&&s[n]>='0'){
if(sum*10+s[n]-'0'<=pow(2,31)-1){
sum=sum*10+s[n]-'0';
n++;
}else{
if(op){
return -pow(2,31);
}
else{
return pow(2,31)-1;
}
}
}
if(op)
sum=-sum;
return sum;
}
};