https://leetcode.com/problems/string-to-integer-atoi/
Implementatoito 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
这类题首先要做的是弄清题意,即input 是什么样的
here:
- contains space
- contains sign +/-
- contains non-numerical character
- might overflow
for 1, remove leading whitespace
for 2, read and mark
for 3, jump out of read loop
for 4, just like previous problem. but we can't use the rule ((a * 10 + b) - b) / 10 == a to check.
instead, we can use a long variable to save tmp value and compare with max/min
or compare by using last result: res, and current digit d
if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE/10 && d > Integer.MAX_VALUE%10))
这里我们直接把Integer.MIN_VALUE 当做overflow case 但不影响结果
not funny