[LeetCode] 9.Palindrome Number
- 题目描述
- 解题思路
- 实验代码
题目描述
Determine whether an integer is a palindrome. Do this without extra space.
解题思路
题目很简单:判断一个整数是否为回文数。那么首先要明白一个概念,什么是回文数:设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。
由题目提示可知,负数一定不是回文数,那么我们就需要找非负整数里的回文数,首先我们要知道它的特点,就是n的各位数字反向排列所得自然数n1与n相等。知道这个特点以后问题就很简单了,只需想办法比较相对位置是否相等就可以了,方法很多。
实验代码
/**
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0))
return false;
int sum = 0;
while (x > sum) {
sum = sum * 10 + x % 10;
x = x / 10;
}
return (x == sum) || (x == sum / 10);
}
};