您的位置:首页 > 其它

leetcode中字符串转化为数字

2016-10-11 21:23 127 查看


8. String to Integer (atoi

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

fas

大概就是说,我们在字符串的前面可以加入空格,和数字的符号+-,然后数字中间不能有其它字符,代码如下

int myAtoi(char* str) {
if(*str==NULL)
return 0;
int res=0;
int sign=1;
int i=0;
while(isspace(*str)) str++;
if(str[0]=='-'){
sign=-1;
i++;
}
else if(str[0]=='+'){
sign=+1;
i++;
}else{
sign=+1;
}
while(str[i]>='0'&&str[i]<='9'){
if(res>INT_MAX/10||(res==INT_MAX/10&&str[i]-'0'>7)){
if(sign==1) return INT_MAX;
else return INT_MIN;
}
res=10*res+(str[i++]-'0');
}
return sign*res;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法