LeetCode C++ 9. Palindrome Number 简单
发布日期:2021-07-01 02:47:47
浏览次数:2
分类:技术文章
本文共 1107 字,大约阅读时间需要 3 分钟。
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121Output: true
Example 2:
Input: -121Output: falseExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10Output: falseExplanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
题意:判断一个整型数据是否是一个回文数。
思路1:可以转换为字符串,然后 reverse
和原串对比。代码:
class Solution { public: bool isPalindrome(int x) { string s = to_string(x), t = s; reverse(t.begin(), t.end()); return s == t ? true : false; }};
思路2:将原数值转为新的回文数值,然后对比。注意,转换过程中可能出现溢出,因此使用 long long
。另外,负数一定不是回文数。代码:
class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; else { long long rev = 0, t = x; while (t) { rev = rev * 10 + t % 10; t /= 10; } return x == rev ? true : false; } }};
转载地址:https://memcpy0.blog.csdn.net/article/details/106654724 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
表示我来过!
[***.240.166.169]2024年04月10日 03时05分13秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
python装饰器学习总结
2019-05-02
我在Facebook学到的10个经验
2019-05-02
c语言知识点补遗
2019-05-02
python开发总结五
2019-05-02
EL、JSTL、servlet
2019-05-02
2 QCreator调试并查看源码
2019-05-02
4 Qt 之 pro 配置多个子工程/子模块
2019-05-02
12 Qt 之 QToolBox、QLCDNumber
2019-05-02
32 Qt 之绘图之绘制一个漂亮的西瓜
2019-05-02
35 Qt 之绘制闪烁文本
2019-05-02
QT知识点总结(一)
2019-05-02
Unix环境变量--文件操作
2019-05-02
Unix环境变量--进程管理
2019-05-02
Unix环境变量--线程基础
2019-05-02
tinyhttpd源码学习1
2019-05-02
Plus One
2019-05-02
Reverse Linked List II
2019-05-02
涨姿势:为啥MySQL官方不推荐使用uuid或者雪花id作为主键?
2019-05-02
一个小小的签到功能,到底用MySQL还是Redis?
2019-05-02
36岁退休!阿里 P8 六年实现“财务自由”,裸辞环游世界!
2019-05-02