本文主要是介绍LeetCode 题解(18): String to Integer (atoi),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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.
题解:
需要注意各种特殊输入,比如字符串开始有0或有空格,比如加减号,比如有字母出现,超出int的表示范围时(INT_MAX)需要根据符号返回对应的值(INT_MAX或INT_MIN)。isdigit()函数很省事,可以记住。
class Solution {
public:int atoi(const char *str) {long long result = 0;assert(str != NULL);bool positive = true;while(*str == '0' || *str == ' '){str++;}if(*str == '-'){positive = false;str++;}else if(*str == '+'){positive = true;str++;}while(isdigit(*str)){if(*str - '0' >= 0 && *str - '9' <= 0){result = result * 10 + (*str - '0');if(result > INT_MAX && positive)return INT_MAX;else if(result > INT_MAX && !positive)return INT_MIN;str++;}}if(positive)return result;elsereturn (0 - result);}
};
这篇关于LeetCode 题解(18): String to Integer (atoi)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!