https://leetcode.com/problems/reverse-integer/

Reverse digits of an integer.

Example1:x = 123, return 321
Example2:x = -123, return -321

最初想法: 转换为string 然后 reverse integer (we also need to process the negative sign) -> reverse string


这是一道模拟题,但这题的核心是做题习惯,弄清楚requirement first. Don't rush into coding.

就如题目中的提示所说:

  1. what should we output if last digit is 0. (如果需要为首0, 那只能用string reverse)
  2. reverse integer might lead to overflow. What should we output if overflow (here is return 0)

对于第二个问题怎么样判断是否overflow?

Integer in java range [-2^31, 2^31 - 1] (about +/-2 billion)

当overflow之后这个int 值就会变成其他绝对值较小的数,所以不能简单的大小比较 (除非我们用更大的一个type, like long save the temporary result)

换一种思路: 假如number a*10 + b = c overflow 了,我们再转换回去将得不到原来的数, 即 (c - b) / 10 != a

但是要注意 假如 a = 214748364 b = 8, 公式还是会成立。 但是这种case在这不存在因为原来的数为8billion (impossible)

因为原来的数是倒序的即 b * 10 + reverse(a)

tips: in java modular operation % ==> sign of remainder depends on sign of dividend (link

18 % 10 = 8

18 % -10 = 8

-18 % 10 = -8

-18 % 10 = -8

results matching ""

    No results matching ""