LeetCode 9. 回文数
LeetCode 回文
2023-06-13 09:13:26 时间
文章目录
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
相关文章
- leetcode 258. 各位相加 js 实现
- leetcode 78. 子集 js 实现
- [LeetCode]238. 除自身以外数组的乘积
- 日拱一卒,LeetCode周赛287,训练你的逆向思维
- [LeetCode 验证回文串] | 刷题打卡
- leetcode 647. 回文子串 js实现
- leetcode 5. 最长回文子串
- LeetCode 680. 验证回文字符串 Ⅱ
- Leetcode分类——递归、回溯、分治
- 秀到起飞!LeetCode官方推出算法面试指导手册(代码版)限时开源
- 前端工程师leetcode算法面试必备-二叉树深度广度遍历
- 【day08】LeetCode(力扣)每日一刷[409. 最长回文串 ][144. 二叉树的前序遍历][589. N 叉树的前序遍历 ]
- LeetCode笔记:Weekly Contest 318
- LeetCode | 括号生成
- LeetCode - #71 简化路径
- golang刷leetcode:BM79 打家劫舍(二)
- leetcode 二分查找 35. Search Insert Position
- LeetCode | 合并两个有序数组
- LeetCode 知识点集成