Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
將一個(gè)整數(shù)中的數(shù)字進(jìn)行顛倒,當(dāng)顛倒后的整數(shù)溢出時(shí),返回 0 (標(biāo)記為 32 位整數(shù))。
分析
通過取余得到最后一位,循環(huán),對于溢出進(jìn)行判斷即可
代碼
public int reverse(int x) {
int result = 0;
while(x != 0) {
int tail = x % 10;
int newResult = result * 10 + tail;
if((newResult-tail)/10 != result)
return 0;
result = newResult;
x = x/10;
}
return result;
}
image.png