您的位置:首页 > 其它

leetcode 8. String to Integer (atoi)

2017-04-18 11:24 501 查看
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.

Update (2015-02-10):

The signature of the 
C++
 function had been updated. If you still see your function signature
accepts a 
const char *
 argument, please click the reload button  to
reset your code definition.

思路:先处理字符串中是否有空格,接着将每个字符串中的数字转换成数字,最后判断是否溢出即可。

class Solution {
public:
int myAtoi(string str) {
if(str.empty()) return 0;
int i=0,sign=1;
while(i+1<str.size()&&isspace(str[i])) ++i;
long res=0;
if(str[i]=='-'||str[i]=='+') sign=44-str[i++];
while(i<str.size()){
if(isdigit(str[i])) res=10*res+str[i++]-'0';
else return res*sign;
if(res>INT_MAX) return sign==-1?INT_MIN:INT_MAX;
}
return res*sign;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息