分类: Java
2015-01-19 21:22:51
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.
解决思路:题目本身并不难,难在判断输入的合法性以及转换后的overflow问题,OJ本身给出了以下几个提示:
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.
首先是字符开始的空白字符的处理,需要找到第一个非空白字符(本人并未考虑到这一情况),然后是一个非空白字符的处理,分为四种情况:+、-、数字、其他字符,再然后就是overflow的问题。这一个题目主要考察的是考虑问题的全面性,在程序员面试宝典中有类似题目的C解法。这里给出JAVA解法:点击(此处)折叠或打开