题目
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
输入 | 输出 | 解释 | |
---|---|---|---|
示例1 | 121 | true | |
示例2 | -121 | false | 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 |
示例3 | 10 | false | 从右向左读, 为 01 。因此它不是一个回文数。 |
解决方案
方法一
在这之前可以先判断这个数字是不是负数,因为负数一定不是回文数,直接返回false即可;
如果是个位数,那么一定是回文数;
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
if(x/10==0) return true;
long long y = 0;
int temp = x;
while(temp != 0)
{
y = y * 10 + temp % 10;
temp =temp / 10;
}
return x == y;
}
};
解释:为什么用longlong
因为int是32位,那么最大的数字是2^31-1=2147483647;
如果我输入进去的数字是 2000000009,
那么我反转之后的数 9000000002 显然超出了int能承受的最大范围,所以这个时候需要用一个存储范围的longlong来接收反转之后的数字;
方法二
为了防止int越界情况,可以将数字变成字符串后再反转,如果翻转后的字符串跟原本的字符串一样,那么这个数字是回文字数;
将数字转换成字符串,string temp=to_string();
-
字符串反转此时是一个对于我来说新的知识点:
reverse(beg,end) 和 reverse_copy(sourceBeg,sourceEnd,destBeg) -
reverse()是将区间[beg,end)内的元素全部逆序;
- reverse_copy()会将源区间[sourceBeg,sourceEnd)内的元素复制到"以destBeg起始的目标区间",并在复制过程中颠倒安置次序;
reverse_copy()返回目标区间内最后一个被复制元素的下一个位置,也就是第一个未被覆盖的元素;
- reverse() 与 reverse_copy()代码示范:
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[10]={0,1,2,3,4,5,6,7,8,9};
int b[10]={0};
reverse(a,a+10); //第二个参数是数组最后一个元素的下一个地址
for(int i=0;i<10;++i)
{
cout<<a[i]<<" ";
}
cout<<endl;
reverse_copy(a,a+10,b); //倒序放入b数组中
for(int i=0;i<10;++i)
{
cout<<b[i]<<" ";
}
cout<<endl;
}
- 执行结果:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
if(x/10==0) return true;
string temp=to_string(x);
string temp2=temp;
reverse(temp2.begin(),temp2.end());
return temp==temp2;
}
};
- 用reverse_copy(temp.begin(),temp.end(),temp2.begin());
class Solution {
public:
bool isPalindrome(int x)
{
if(x<0) return false;
if(x/10==0) return true;
string temp = to_string(x);
string temp2;
temp2.resize(temp.size());//给temp2和temp一样的空间长度
reverse_copy(temp.begin(), temp.end(), temp2.begin());
return temp==temp2;
}
};
方法三
为了不让反转的数字超过int范围并且不需要变成字符串,我们可以只反转一半的数字;
例如:123321 只需将后半部分的‘’321‘’反转成‘’123‘’,再与前半部分的“123”比较,此时相同,则是回文数,若不同则不是。
class Solution {
public:
bool isPalindrome(int x) {
if(x<0||(x%10==0&&x!=0)) return false; // [^1]
int latter=0;
while(x>latter)
{
latter=latter*10+x%10;
x=x/10;
}
return x==latter||x==latter/10; //注释2
}
};
- 注释1:如果最后一位是0,那么为了使得这个数是回文数,首位也应该是0.那么只有0满足条件
如若不加此限定,10会判定为true
注释2:当数字x为奇数长度时,通过latter/10去掉中位数,例如12321
latter=321,反转后为123,此时x=12,latter/10去掉中位数3,此时latter/10==x,是回文数。