LeetCode 9. 回文数
发布日期:2021-07-01 03:13:46 浏览次数:2 分类:技术文章

本文共 1137 字,大约阅读时间需要 3 分钟。

文章目录

1. 题目信息

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

示例 1:输入: 121输出: true示例 2:输入: -121输出: false解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。示例 3:输入: 10输出: false解释: 从右向左读, 为 01 。因此它不是一个回文数。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/palindrome-number

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 先排除负数,后缀是0的数(除开0)
  • 分别取出个位、十位。。。乘以10,乘以10,得到反向数的值
  • 比较反向数与原数(注意可能溢出)

在这里插入图片描述

class Solution {
// C++public: bool isPalindrome(int x) {
if(x < 0 || x%10 == 0 && x != 0) return false; long reverse = 0; int pos, copy = x; while(copy) {
pos = copy%10; copy /= 10; reverse = reverse*10 + pos; } return reverse == x; }};

or

转字符串处理

class Solution {
//c++public: bool isPalindrome(int x) {
string s1 = to_string(x); string s2 = s1; reverse(s2.begin(),s2.end()); return s1==s2; }};
class Solution:# py3    def isPalindrome(self, x: int) -> bool:        a = str(x)        return "".join(reversed(a))==a

or

class Solution:# py3    def isPalindrome(self, x: int) -> bool:        a = str(x)        return a[::-1]==a

转载地址:https://michael.blog.csdn.net/article/details/100168231 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 160. 相交链表
下一篇:LeetCode 90. 子集 II(回溯+剪枝)

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月22日 11时11分49秒