Determine whether an integer is a palindrome. Do this without extra space.
判斷一個數整數是不是迴文?例如121,1221就是迴文,好吧,直接利用前面寫過的【Leet Code】Reverse Integer——“%”你真的懂嗎?
不過這裏要考慮翻轉後,數值溢出的問題,代碼如下:
/*
//first method
class Solution {
public:
bool isPalindrome(int x)
{
long long temp = x;
long long ret = 0;
bool isNegative = false;
if (temp < 0)
{
return false;
}
while (temp)
{
ret = ret * 10 + temp % 10;
temp /= 10;
}
if(x == ret)
{
return true;
}
else
{
return false;
}
}
};
*/
當然,我們還有更好的方法,其實,初見這個題目,第一個想法是取頭取尾進行比較,然後把頭尾去掉,再循環,直到數值爲個位數爲止:
class Solution {
public:
bool isPalindrome(int x)
{
if (x < 0)
{
return false;
}
int divisor = 1;
while (x / divisor >= 10)
{
divisor *= 10;
}
while (x)
{
if (x / divisor != x % 10)
{
return false;
}
x = (x % divisor) / 10;
divisor /= 100;
}
return true;
}
};