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
accepts a
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;
}
};
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;
}
};
相关文章推荐
- leetcode 54: String to Integer (atoi)
- Leetcode : String to Integer (atoi)
- LeetCode-String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- leetcode -- String to Integer (atoi)
- leetcode 54: String to Integer (atoi)
- [leetcode]String to Integer (atoi)
- LeetCode-String to Integer (atoi)
- [leetcode刷题系列]String to Integer (atoi)
- LeetCode:String to Integer (atoi)
- [leetcode] String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- leetcode String to Integer (atoi)Dec 27 '117626 / 35090
- [LeetCode] String to Integer (atoi) 解题报告
- LeetCode 8 - String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- LeetCode :String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- LeetCode: String to Integer (atoi)