标签:style blog http io color ar os for sp
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.
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.
思路:要注意的细节较多
1)输入为空指针
2)忽略开头空格字符,并且对第一个非空格字符做‘+’,‘-’号的判断(可选,不是必须)
3)如果碰到不是数字的字符,则停止转换
4)如果正溢出,则返回INT_MAX,如果负溢出则返回INT_MIN
5)如果第一个非空字符串不是有效的数字(只对第一个非空字符串判断),或者字符串中只有空格,那么返回0。
时间复杂度O(n),空间复杂度O(1)
class Solution { public: int atoi(const char *str) { if (str == NULL) return 0; int i = 0; int length = strlen(str); int sign = 1; long long num = 0; while (str[i] == ‘ ‘ && i < length) ++i; if (str[i] == ‘+‘) { sign = 1; ++i; } else if (str[i] == ‘-‘) { sign = -1; ++i; } for (; i < length; ++i) { if (str[i] < ‘0‘ || str[i] > ‘9‘) break; num = num * 10 + (str[i] - ‘0‘); } if (num > INT_MAX || num < INT_MIN) return sign == 1 ? INT_MAX : INT_MIN; return sign * num; } };
[LeetCode] Single NumberString to Integer (atoi)
标签:style blog http io color ar os for sp
原文地址:http://www.cnblogs.com/vincently/p/4074119.html