当前位置:网站首页>【每日一道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;
}
}
运行结果:
边栏推荐
猜你喜欢
Remember a gorm transaction and debug to solve mysql deadlock
字符串常用方法
The state status is displayed incorrectly after the openGauss switch
Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
列表常用方法
Nanoprobes免疫测定丨FluoroNanogold试剂免疫染色方案
灰度传感器、、、diy原理。。图
Use DBeaver for mysql data backup and recovery
CASE2023
AI目标分割能力,无需绿幕即可实现快速视频抠图
随机推荐
Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
What to study after the PMP exam?The soft exam ahead is waiting for you~
Reflex WMS Intermediate Series 7: What should I do if I want to cancel the picking of an HD that has finished picking but has not yet been loaded?
AI target segmentation capability for fast video cutout without green screen
1688API
周鸿祎称微软抄袭,窃取360安全模式
一次SQL优化,数据库查询速度提升 60 倍
Docker-compose安装mysql
ALCCIKERS Shane 20191114
NIO's Sword
OC和Swift语言的区别
canal同步Mariadb到Mysql
isa指针使用详情
The failure to create a role in Dahua Westward Journey has been solved
PAT甲级打卡-1001-1004
Flask 报错:WARNING This is a development server. Do not use it in a production deployment
leetcode / anagram in string - some permutation of s1 string is a substring of s2
内卷的正确打开方式
Chopper webshell feature analysis
1688以图搜货