力扣: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.反转全部数字

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

#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除外

#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)
比较:
两种方法相比较,第二种方法运算时间更短,占用的内存更少

力扣官方为第二种:
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. 回文数

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值