鏈接: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.
翻譯:確定一個整數(shù)是否是回文數(shù)。不能使用額外的空間。
一些提示:
負(fù)數(shù)能不能是回文數(shù)呢?(比如酣倾,-1)
如果你想將整數(shù)轉(zhuǎn)換成字符串,但要注意限制使用額外的空間。
你也可以考慮翻轉(zhuǎn)一個整數(shù)玫镐。
然而,如果你已經(jīng)解決了問題"翻轉(zhuǎn)整數(shù)"怠噪,
那么你應(yīng)該知道翻轉(zhuǎn)的整數(shù)可能會造成溢出恐似。
你將如何處理這種情況?
這是一個解決該問題更通用的方法傍念。
思路:什么是回文矫夷?指的是“對稱”的數(shù),即將這個數(shù)的數(shù)字按相反的順序重新排列后憋槐,所得到的數(shù)和原來的數(shù)一樣双藕。
這道題可以看成要計算一個數(shù)字是否是回文數(shù)字,我們其實就是將這個數(shù)字除以10阳仔,保留他的余數(shù)忧陪,下次將余數(shù)乘以10,加上這個數(shù)字再除以10的余數(shù)近范。依此類推嘶摊,看能否得到原來的數(shù)。
注:負(fù)數(shù)不是回文數(shù)字评矩,0是回文數(shù)字.
參考代碼:
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;
}
}