当前位置:网站首页>【每日一道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;
}
}运行结果:

边栏推荐
- 【CNN记录】tensorflow slice和strided_slice
- How engineers treat open source
- ofstream,ifstream,fstream read and write files
- BI-SQL丨WHILE
- Chopper webshell feature analysis
- CASE2023
- 永磁同步电机36问(二)——机械量与电物理量如何转化?
- 2022-07-30 mysql8 executes slow SQL-Q17 analysis
- The state status is displayed incorrectly after the openGauss switch
- 1688以图搜货
猜你喜欢

【web】Understanding Cookie and Session Mechanism

【Unity入门计划】2D Game Kit:初步了解2D游戏组成

局部敏感哈希:如何在常数时间内搜索Embedding最近邻

工程师如何对待开源

AI target segmentation capability for fast video cutout without green screen

字典常用方法

The first time I wrote a programming interview question for Niu Ke: input a string and return the letter with the most occurrences of the string

Install mysql using docker

面对职场“毕业”,PM&PMO应该如何从容的应对?如何跳槽能够大幅度升职加薪?

The state status is displayed incorrectly after the openGauss switch
随机推荐
亲身经历过的面试题
列表常用方法
analog IC layout-Design for reliability
Docker-compose安装mysql
Flask之路由(app.route)详解
永磁同步电机36问(二)——机械量与电物理量如何转化?
GTK RGB图像绘制
AWR分析报告问题求助:SQL如何可以从哪几个方面优化?
Nanoprobes Polyhistidine (His-) Tag: Recombinant Protein Detection Protocol
工程师如何对待开源
Nanoprobes多组氨酸 (His-) 标签标记:重组蛋白检测方案
使用self和_(下划线)的区别
MySQL - CRUD operations
Chapter 7 Noise analysis
2022-08-01 反思
Win Go development kit installation configuration, GoLand configuration
60 Feature Engineering Operations: Using Custom Aggregate Functions【Favorites】
微信小程序异步回调函数恶梦和解决办法
2022-08-01 安装mysql监控工具phhMyAdmin
2022.8.1-----leetcode.1374