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.
將一個整數(shù)中的數(shù)字進行顛倒,當顛倒后的整數(shù)溢出時,返回 0 (標記為 32 位整數(shù))。
分析
通過取余得到最后一位,循環(huá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