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.
解法1:
这题要考虑的corner case比较多,也是这题的难点。
corner case有:
empty string
string with space
string with positive or negative sign
string with non-digit numbers
overflow integer
对于overflow的处理有两种情况。一个是当前的total乘以10之后超过Integer.MAX_VALUE,由于不能直接比total * 10 > Integer.MAX_VALUE, 我们可以换一种比法。
用Integer.MAX_VALUE / 10 < total 表示判断标准。
但是这又有一种情况就是Integer.MAX_VALUE / 10 是整数除法,可能会有遗漏的情况是最后一位不同。
那么就需要排除Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit 的情况。
Java