Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
題目:
給一個32位元的整數,把它反轉過來。
注意:
integer的範圍為 −231, 231 − 1 ,如果反轉溢出的話則回傳0。
解答:
public class ReverseInteger7 {
public static void main(String[] args) {
System.out.print(reverse(123));
}
public static int reverse(int x) {
//考慮反轉後可能溢位故用長整數來儲存
long r = 0;
while (x != 0) {
//把x的最小位數取出,反轉成r的最大位數
r = r * 10 + x % 10;
x = x / 10;
}
//判斷是否會溢位
if (r > Integer.MAX_VALUE || r < Integer.MIN_VALUE) {
return 0;
} else {
return (int)r;
}
}
}