您的位置:首页 > 其它

LeetCode OJ刷题历程——Sting to Integer(atoi)

2016-03-06 13:59 197 查看
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.Requirements for atoi:The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


以上是题目要求。
本题也较为简单,需要注意的,如题所说,注意考虑所有可能的输入,下面贴出代码:

class Solution {
public:
int myAtoi(string str) {
vector<int> p;
bool positive_sign = true;
long long int sum = 0;
bool first = true;
for(size_t i = 0;i<str.size();i++){
if(first){
if(str[i] == '-' || (str[i] <='9' && str[i] >='0') || str[i] == '+'){
first = false;
if(str[i] == '-'){
positive_sign = false;
continue;
}
else if(str[i] == '+')
continue;
}else if(str[i] != ' ')
return 0;
}if(!first){
if(str[i] <='9' && str[i] >='0'){
p.push_back(str[i]  - '0');
//j++;
}
else
break;
}
}
if((p.size()>10))
if(positive_sign)
return 2147483647;
else
return -2147483648;
else{
for(int i = 0;i<p.size();i++){
sum = sum*10 +p[i];
}
if((sum>>31)>0)
if(positive_sign)
return 2147483647;
else
return -2147483648;
else
return positive_sign?sum:-sum;
}
}
};
最需要注意的是,如何判断转换后的数超出界限问题,有可能超出long long int.......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: