您的位置:首页 > 职场人生

[LeetCode] String to Integer (atoi)

2014-01-07 02:01 260 查看
问题:

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.

spoilers alert... click to show requirements for atoi.

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 (-214748
4000
3648) is returned.

分析:
没什么技巧,就是直接做。注意处理out of range的情况即可。

代码:

class Solution {
public:
int atoi(const char *str) {
if (!str) return 0;
bool positive = true;
int result = 0;
const char * current = str;
bool error = false;
while (*current == ' ')
current ++;
if (*current == '-') {
positive = false;
current ++;
}
else if (*current == '+') {
positive = true;
current ++;
}
while (*current) {
if (*current < '0' || *current > '9') {
break;
}
int num = *current - '0';
if ((result == 214748364 && num > 7 && positive) ||
(result == 214748364 && num > 8 && !positive) ||
(result > 214748364)
)
return positive ? INT_MAX : INT_MIN;
result = result * 10 + num;
current ++;
}
return positive ? result : -result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 面试