当前位置:网站首页>【LeetCode】9、回文数
【LeetCode】9、回文数
2022-06-22 14:37:00 【小曲同学呀】
9、回文数
题目:
给你一个整数 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
进阶:你能不将整数转为字符串来解决这个问题吗?
解题思路:
题目中说,我们不能将整数转为字符串来解决这个问题,那我们可以用数学的方式来解决。
- 首先如果是负数则一定不是回文数,直接返回 false;
- 如果是正数,则将其倒序数值计算出来,然后比较和原数值是否相等
- 如果是回文数则相等返回 true,如果不是则不相等 false
- 比如 123 的倒序 321,不相等;121 的倒序 121,相等
参考代码:
class Solution {
public boolean isPalindrome(int x) {
if(x < 0)
return false;
int cur = 0;
int num = x;
while(num != 0) {
cur = cur * 10 + num % 10;
num /= 10;
}
return cur == x;
}
}
整体来说,代码和思路都非常简单。

边栏推荐
- (pytorch进阶之路二)word embedding 和 position embedding
- 历时100天、小鱼搭建了个机器人交流社区!!现公开邀请版主中!
- Trust level of discover
- Binary search (integer binary)
- 对领域驱动设计DDD理解
- How MySQL modifies a field to not null
- 问一下想获取到sqlserver的start_lsn有好的办法吗?
- SDVO:LDSO+语义,直接法语义SLAM(RAL 2022)
- 快速玩转CI/CD图形化编排
- [Newman] postman generates beautiful test reports
猜你喜欢

CVE-2022-0847(提权内核漏洞)

On the routing tree of gin

Development status of full color LED display

【VTK】模型旋转平移

极致效率,云原生数据库TDSQL-C安身立命的根本

Community article | mosn building subset optimization ideas sharing

Jenkins automatically triggers compilation by checking code submissions

C# 实现插入排序

Once, I had 5 part-time jobs just to buy a new earring for my girlfriend

HMS core news industry solution: let technology add humanistic temperature
随机推荐
华为机器学习服务银行卡识别功能,一键实现银行卡识别与绑定
2020年蓝桥杯省赛真题-走方格(DP/DFS)
打新债安全性有多高
三菱机械臂demo程序
标准化、最值归一化、均值归一化应用场景的进阶思考
Recommend several AI Intelligent Platforms
希尔排序的简单理解
How MySQL modifies a field to not null
Scala language learning-06-differences between name passing parameters, value passing parameters and function passing parameters
Discourse 的信任级别
(pytorch进阶之路二)word embedding 和 position embedding
天安科技IPO被终止:曾拟募资3.5亿 复星与九鼎是股东
(pytorch advanced path 2) word embedding and position embedding
排序之归并排序
Merge sort of sorting
TDengine 连接器上线 Google Data Studio 应用商店
Ml notes matrix fundamental, gradient descent
又可以这样搞nlp(分类)
Is pioneer futures reliable? How to open a futures account safely?
DDD understanding of Domain Driven Design