/*
* 以下程序把一個整數翻轉(8765變爲:5678)
*/
public static void main(String[] args) {
int n = 87655;
int m = 0;
while(n!=0){
m = m*10 + n % 10; // 填空
n = n / 10;
}
System.out.println(m);
}
/*
* 給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
* 注意:
* 假設我們的環境只能存儲得下 32 位的有符號整數,則其數值範圍爲 [−231, 231 − 1]。
* 請根據這個假設,如果反轉後整數溢出那麼就返回 0。
*/
public static int reverse(int x) {
int m = 0;
while (x != 0) {
if (m > Integer.MAX_VALUE / 10 || (m == Integer.MAX_VALUE / 10 && (x % 10) > 7)
|| (m < Integer.MIN_VALUE / 10)
|| (m == Integer.MIN_VALUE / 10 && (x % 10)< -8)) {
return 0;
}
m = m * 10 + x % 10;
x = x / 10;
}
return m;
}