[容易]反转整数

[容易]反转整数

[题]

Given a 32-bit signed integer, reverse digits of an integer, assume that your function returns 0 when the reversed integer overflow

Input: 123
Output : 321

Input : -123
Output: -321

Input: 120
Output: 21

[解]

How to represent 32-bit signed integer?

n-bit signed integer: \( -2^{n-1}\) ~ \(2^{n-1} – 1\)
n-bit unsigned integer: \(2^{n}-1\)

How to check overflow?

使用long保存结果并与上下界比较

How to get last digit?

123 % 10 = 3
-123 % 10 = -3

Code