本文主要是介绍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.
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.数字可能有符号
解法很简单,详见代码:
class Solution {
public:int myAtoi(string str) {long result = 0;int sign = 1;int i = 0;while(i < str.length() && str[i] == ' ') i++;if(str[i] == '-' || str[i] == '+'){sign = (str[i++] == '-') ? -1 : 1;}while(i < str.length() && '0' <= str[i] && str[i] <= '9'){result = result * 10 + (str[i++] - '0');if(result * sign >= INT_MAX) return INT_MAX;if(result * sign <= INT_MIN) return INT_MIN; }return result * sign;}
};
有不懂的可以跟我交流哈~~
这篇关于String to Integer (atoi)问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!