力扣: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. 回文数

相关推荐
NAGNIP5 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队6 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja11 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下11 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶11 小时前
算法 --- 字符串
算法
博笙困了11 小时前
AcWing学习——差分
c++·算法
NAGNIP11 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP11 小时前
大模型微调框架之LLaMA Factory
算法
echoarts11 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客11 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法