当前位置:网站首页>【每日一道LeetCode】——9. 回文数
【每日一道LeetCode】——9. 回文数
2022-08-02 02:36:00 【月亮嚼成星~】
目录
原题:
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。
示例 1:
输入:x = 121
输出:true示例 2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。示例 3:
输入:x = 10
输出:false
解释:从右向左读, 为 01 。因此它不是一个回文数。解题思路 :
首先正确理解回文数的概念。我们知道负数和末尾为0的数不可能是回文数,所以这两个作为边界,为false。除此之外的数为回文数。首先可以这样解题:判断这个数的第一位和最后一位是否一致,如果不一样,则不是回文数,每次都比较两个,也就是要设置一个left,一个right,比较left和right是否一致,不一致就返回false。
通过取整和取余操作获取整数中对应的数字进行比较。
举个例子:
1221 这个数字。通过计算 1221 / 1000, 得首位1
通过计算 1221 % 10, 可得末位 1
进行比较
再将 22 取出来继续比较
代码实现:
class Solution {
public boolean isPalindrome(int x) {
//边界判断
if(x<0||(x%10==0&&x!=0)){
return false;
}
int ret=1;
while(x/ret>=10){
ret*=10;
}
while(x>0){
int left=x/ret;
int right=x%10;
if(left!=right){
return false;
}
x=(x%ret)/10;
ret/=100;
}
return true;
}
}运行结果:

边栏推荐
- BioVendor人俱乐部细胞蛋白(CC16)Elisa试剂盒研究领域
- 架构:分布式任务调度系统(SIA-Task)简介
- Use DBeaver for mysql data backup and recovery
- 记一个gorm初始化的坑
- 【CNN记录】tensorflow slice和strided_slice
- OC中成员变量,实例变量和属性之间的区别和联系
- Analysis of the status quo of digital transformation of manufacturing enterprises
- ALCCIKERS Shane 20191114
- Ringtone 1161. Maximum In-Layer Elements and
- AI target segmentation capability for fast video cutout without green screen
猜你喜欢
随机推荐
openGauss切换后state状态显示不对
Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
The principle and code implementation of intelligent follower robot in the actual combat of innovative projects
拼多多借力消博会推动国内农产品品牌升级 看齐国际精品农货
yaml
考完PMP学什么?前方软考等着你~
analog IC layout-Design for reliability
How to adjust the cross cursor too small, CAD dream drawing calculation skills
国标GB28181协议EasyGBS平台兼容老版本收流端口的功能实现
60 Feature Engineering Operations: Using Custom Aggregate Functions【Favorites】
FOFAHUB使用测试
2022-08-01 mysql/stoonedb慢SQL-Q18分析
周鸿祎称微软抄袭,窃取360安全模式
EFCore 反向工程
2022-08-01 Reflection
淘宝详情.
Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
Lombok
53. 最小的k个数
The failure to create a role in Dahua Westward Journey has been solved








