力扣:9. 回文数

力扣:9. 回文数

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

例如,121 是回文,而 123 不是。

示例 1:

输入:x = 121

输出:true

示例 2:

输入:x = -121

输出:false

解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:

输入:x = 10

输出:false

解释:从右向左读, 为 01 。因此它不是一个回文数。

提示:

-231 <= x <= 231 - 1

思路

1.反转全部数字

负数都不是回文数

反转后的数字与原来的数字进行比较,相等则为回文数,否则不是

cpp 复制代码
#include <iostream>
using namespace std;

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)
            return false;
        
        long palindrome = 0; // 变量类型用 int 会溢出,用 long
        int num = x; // 要多定义一个变量 num 存放 x 的值,如果直接用 x,最后判断时 x 的值会改变
        while(num > 0) {
            palindrome = palindrome * 10 + num % 10;
            num /= 10;
        }
        
        return x == palindrome;
    }
};

int main() {
    Solution solution;
    int num = 12321;

    if(solution.isPalindrome(num)) {
        std::cout << num << " is a palindrome number." << std::endl;
    } else {
        std::cout << num << " is not a palindrome number." << std::endl;
    }

    return 0;
}

2.反转一半的数字

负数都不是回文数

因为高位不能为0,所以个位是0的数不是回文数,0除外

cpp 复制代码
#include<iostream>
using namespace std;
class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0||(x!=0&&x%10==0))
        return false;
        int palindrome=0;
        while(x>palindrome){
            palindrome=palindrome*10+x%10;
            x/=10;
        }
        return x==palindrome||x==palindrome/10;//如果此回文数的个数为奇数则x==palindrome/10,为偶数则x==palindrome
    }
};

int main()
{
	Solution solution;
	int x = 12321;
	bool result = solution.isPalindrome(x);
	if(result){
		cout <<  x << " is palindrome" << endl;
	}
	else {
		cout << x << " is not palindrome" <<endl;
	}
	return 0;
}

复杂度分析:

时间复杂度:O(logn),每次循环输入除以10

空间复杂度:O(1)

比较:

两种方法相比较,第二种方法运算时间更短,占用的内存更少

力扣官方为第二种:
cpp 复制代码
class Solution {
public:
    bool isPalindrome(int x) {
        // 特殊情况:
        // 如上所述,当 x < 0 时,x 不是回文数。
        // 同样地,如果数字的最后一位是 0,为了使该数字为回文,
        // 则其第一位数字也应该是 0
        // 只有 0 满足这一属性
        if (x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int revertedNumber = 0;
        while (x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }

        // 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
        // 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
        // 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
        return x == revertedNumber || x == revertedNumber / 10;
    }
};

题目:力扣:9. 回文数

相关推荐
CoovallyAIHub2 分钟前
线性复杂度破局!Swin Transformer 移位窗口颠覆高分辨率视觉建模
深度学习·算法·计算机视觉
点云SLAM29 分钟前
Eigen中Dense 模块简要介绍和实战应用示例(最小二乘拟合直线、协方差矩阵计算和稀疏求解等)
线性代数·算法·机器学习·矩阵·机器人/slam·密集矩阵与向量·eigen库
renhongxia11 小时前
大模型微调RAG、LORA、强化学习
人工智能·深度学习·算法·语言模型
DdduZe1 小时前
8.19作业
数据结构·算法
PyHaVolask1 小时前
链表基本运算详解:查找、插入、删除及特殊链表
数据结构·算法·链表
高山上有一只小老虎1 小时前
走方格的方案数
java·算法
吧唧霸2 小时前
golang读写锁和互斥锁的区别
开发语言·算法·golang
1白天的黑夜13 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表