Fork me on GitHub

判断回文数(三种解法)—— Leetcode(9)

Leetcode链接:9. Palindrome Number

Palindrome Number,即判断是否为回文数,并且题目要求不能使用额外的空间。
即,不能使用回文串的方法。

在本题中,负数不作为回文数考虑范围之内,但是输入依然可能为负,此时直接返回false即可。

首先,一种容易想到的方法是:将整个数取反后看和原来的数是否相同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool isPalindrome(int x) {
if (x<0)
return false;
long long int sum =0;
long long int origin = x;
while(x)
{
int num = x %10;
sum = sum*10 + num;
x/=10;
}
if(sum == origin)
return true;
else
return false;
}
};

我采用另外一种方法:根据回文数的特点,我们只需要判断左边一半和翻转后的右边一半是否相等即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool isPalindrome(int x) {
// 负数肯定不是,以及首尾不对称的非0数
if(x < 0 || (x % 10 == 0 && x != 0))
return false;
int rev = 0;
while ( x > rev){
rev = rev * 10 + x % 10; //将低位一半的数取反。
x = int (x / 10);
}
//有rev >= x, 奇数情况下需要除去10
return x == rev || x == int(rev/10);
}
};

还有另外一种解法:
类似与采用两个指针。
在循环体中,不断地比较第i位和倒数第i位,直到遇到最中间的1个数字(输入为奇数个数字)或者遇到最中间的2个数字(输入为偶数个数字)时结束。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int l = x / div;
int r = x % 10;
if (l != r) return false;
x = (x % div) / 10; //去掉两边的数
div /= 100;
}
return true;
}

参考链接:

------ 本文结束感谢您的阅读 ------
坚持原创技术分享,您的支持将鼓励我继续创作!