LeetCode9. 回文数

LeetCode9. 回文数:

题目描述:

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

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

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

示例 1:

输入:x = 121

输出:true

示例 2:

输入:x = -121

输出:false

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

示例 3:

输入:x = 10

输出:false

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

提示:

-2^31 <= x <= 2^31 - 1

思路:

1.转换成字符串:翻转一下跟原来的做对比看是否一致

2.将数值进行翻转,对比是否一致

自己写的代码:

思路对了,但是做了很多冗余的判断,很慢,击败8.66%,hh

复制代码
class Solution {
public:
    bool isPalindrome(int x) {
        int res = 0;
        int temp = x;
        if(x < 0) return false;
        while(x)
        {
            if(res > (INT_MAX - x % 10) / 10) return false;
            res = res * 10 + x % 10;
            x /= 10;
        }
        printf("%d", res);
        if(res == temp) return true;
        else return false;
    }
};

转成字符串判断:

复制代码
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return 0;
        string s = to_string(x);
        return s == string(s.rbegin(), s.rend());
    }
};

数值转换方法:

复制代码
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0 ) return 0;
        int y = x;
        long long res = 0;
        while(x)
        {
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res == y;
    }
};
相关推荐
半壶清水1 天前
[软考网规考点笔记]-操作系统核心知识及历年真题解析
网络·网络协议·算法
Tansmjs1 天前
实时数据可视化库
开发语言·c++·算法
WBluuue1 天前
Codeforces 1075 Div2(ABC1C2D1D2)
c++·算法
圣保罗的大教堂1 天前
leetcode 3650. 边反转的最小路径总成本 中等
leetcode
2401_838472511 天前
C++模拟器开发实践
开发语言·c++·算法
s1hiyu1 天前
实时控制系统验证
开发语言·c++·算法
daad7771 天前
V4L2_mipi-csi
算法
2301_765703141 天前
C++代码复杂度控制
开发语言·c++·算法
m0_708830961 天前
C++中的享元模式实战
开发语言·c++·算法
naruto_lnq1 天前
分布式计算C++库
开发语言·c++·算法