連結: https://leetcode.com/problems/palindrome-number/#/description
難度:Easy
題目:9.Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
翻譯:确定一個整數是否是回文數。不能使用額外的空間。
一些提示:
負數能不能是回文數呢?(比如,-1)
如果你想将整數轉換成字元串,但要注意限制使用額外的空間。
你也可以考慮翻轉一個整數。
然而,如果你已經解決了問題"翻轉整數",
那麼你應該知道翻轉的整數可能會造成溢出。
你将如何處理這種情況?
這是一個解決該問題更通用的方法。
思路:什麼是回文?指的是“對稱”的數,即将這個數的數字按相反的順序重新排列後,所得到的數和原來的數一樣。
這道題可以看成要計算一個數字是否是回文數字,我們其實就是将這個數字除以10,保留他的餘數,下次将餘數乘以10,加上這個數字再除以10的餘數。依此類推,看能否得到原來的數。
注:負數不是回文數字,0是回文數字.
參考代碼:
Java
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0)) return false;
int r = 0;
while (x > r) {
r = r * 10 + x % 10;
x = x /10;
}
return x == r || x == r / 10;
}
}