题目: Determine whether an integer is a palindrome. Do this without extra space.
思路分析: 回文判断,题目提示不能使用直接转字符串,不能翻转数字。 那只能一个一个取出数字进行比较了。
C++参考代码:
class Solution
{
public:
bool isPalindrome(int x)
{
if (x < 0) return false;
if (x == 0) return true;
int scale = 1;//标记x的数量级
while (x / scale >= 10)
{
scale *= 10;
}
int left, right;
while (x)
{
left = x / scale;//最最左边的数字
right = x % 10;//最右边的数字
if (left != right) return false;
x -= left * scale;//去掉最左边的数字
x /= 10;//去掉最右边的数字
scale /= 100;//x的数量级较少两级
}
return true;
}
};
C#参考代码:
public class Solution
{
public Boolean IsPalindrome(int x)
{
if (x < 0) return false;
if (x == 0) return true;
int scale = 1;
while (x / scale >= 10)
{
scale *= 10;
}
int left = 0;
int right = 0;
while (x != 0)
{
left = x / scale;
right = x % 10;
if (left != right) return false;
x -= left * scale;
x /= 10;
scale /= 100;
}
return true;
}
}
Python参考代码: 如果使用Python3.x,请将其中的一般除法/换成floor除法//(两个/表示floor除法)
class Solution:
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False
if x == 0:
return True
scale = 1
while x / scale >= 10:
scale = scale * 10
while x != 0:
left = x / scale
right = x % 10
if left != right:
return False
x = x - left * scale
x = x / 10
scale = scale / 100
return True