給出一個 32 位的有符號整數(shù)迫卢,你需要將這個整數(shù)中每位上的數(shù)字進(jìn)行反轉(zhuǎn)倚搬。
示例 1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設(shè)我們的環(huán)境只能存儲得下 32 位的有符號整數(shù),則其數(shù)值范圍為 [?231, 231 ? 1]乾蛤。請根據(jù)這個假設(shè)每界,如果反轉(zhuǎn)后整數(shù)溢出那么就返回 0。
JAVA實(shí)現(xiàn)
class Solution {
public int reverse(int x) {
if (x > Integer.MAX_VALUE || Math.abs(x) > Integer.MAX_VALUE) {
return 0;
}
long res = 0;
int tmp = Math.abs(x);
while (tmp > 0) {
res *= 10;
res += tmp % 10;
if (res > Integer.MAX_VALUE){
return 0;
}
tmp /= 10;
}
return (int)(x > 0 ? res : -res );
}
}