【leetcode】【简单】判断回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
在这里插入图片描述

解法1:数字反转判断相同

利用前面写过的数字反转判断反转后的数据和原数据是否相同

class Solution {
public:
    bool isPalindrome(int x) {
        long rs=0;
        int temp=x;
        for(;x;rs=rs*10+x%10,x/=10);
        return (rs==temp)&&(temp>=0)?true:false;
    }
};

解法2:将数字转化为字符串反转函数判断

class Solution {
public:
    bool isPalindrome(int x) 
    {
        if (x < 0)//负数全部排除
		{
			return false;
		}
		else if (0 <= x && x < 10)//1位数都是
		{
			return true;
		}
		else
		{
			string src, dest;
			while (x)//先将数字转换为字符
			{
				src += x % 10;
				x /= 10;
			}
			dest = src;//记录原字符
			reverse(src.begin(),src.end());//将其反转
			if (dest == src)//若源字符串和反转串不一致就不是回文串
			{
				return true;
			}
			return false;
		}
    }
};
发布了21 篇原创文章 · 获赞 0 · 访问量 336

猜你喜欢

转载自blog.csdn.net/weixin_44225940/article/details/103960021