編程語言是 Java,代碼托管在我的 GitHub 上,包括測試用例。歡迎各種批評指正!
<br />
題目 —— Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
<br >
解答
題目大意
反轉一個整數的所有整數位。解題思路
對于整數取位數,我們一下能想到的方法就是除以 10 取余數,這樣循環取位,就是倒序的,然后我們在另一個整數中 *10 再加上這個余數即可。代碼實現
public class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
int remainder = x % 10;
int newResult = result * 10 + remainder;
if ((newResult - remainder) / 10 != result) {
return 0;
}
result = newResult;
x = x/10;
}
return result;
}
}
-
小結
對于該題目注意兩點:- 循環的跳出條件,因為 x 可正可負,所以等于 0 時退出。
- 翻轉整數可能引起溢出,但是溢出分正負兩種情況,如何判斷溢出呢?這里減去余數以后,再除以 10,判斷和運算之前的結果是否相等即可。