当前位置:网站首页>LeetCode #9.回文数
LeetCode #9.回文数
2022-07-29 05:24:00 【张楚明ZCM】
题目截图

方法一:将整数转为字符串后反转字符再比较
借鉴第整数反转的思路,稍加修改代码,增加一个返回的比较值即可
class Solution:
def isPalindrome(self, x: int) -> bool:
INT_MIN, INT_MAX = -2**31, 2**31-1
if x<INT_MIN or x>INT_MAX:
return False
else:
y = int(str(abs(x))[::-1])
if y<INT_MIN or y > INT_MAX:
return False
else:
return x==y
代码优化
直接比较两各转换后的字符串即可,不需要来回转换。
class Solution:
def isPalindrome(self, x: int) -> bool:
INT_MIN, INT_MAX = -2**31, 2**31-1
if x<INT_MIN or x>INT_MAX:
return False
else:
x = str(x)
return x == x[::-1]代码再优化
class Solution:
def isPalindrome(self, x: int) -> bool:
INT_MIN, INT_MAX = -2**31, 2**31-1
s=str(x)
return True if (x>INT_MIN and x<INT_MAX) and (s == s[::-1]) else False方法二:数学法
负数一定不是回文数,直接返回False。正整数对10取模后变为新的数的头。在对比新旧两个数是否一样。
class Solution:
def isPalindrome(self, x: int) -> bool:
INT_MIN, INT_MAX = -2**31, 2**31-1
y = 0
temp = x
if x < 0:
return False
while temp != 0:
y = y*10 + temp%10
temp//=10
return False if (y>INT_MAX or x>INT_MAX or y<INT_MIN or x<INT_MIN ) else (x == y)还可以考虑回文因为是对称的,其实可以不用全部反转后对比,而是从中间分开,前后对比。
此处不想再写了。
边栏推荐
- DP4301—SUB-1G高集成度无线收发芯片
- FPGA based: moving target detection (supplementary simulation results, available)
- Hal library learning notes-11 I2C
- 多线程和并发
- Ml self study notes 5
- Power electronics: single inverter design (matlab program +ad schematic diagram)
- Huawei cloud 14 days Hongmeng device development -day1 environment construction
- Ml6 self study notes
- 【软件工程之美 - 专栏笔记】24 | 技术债务:是继续修修补补凑合着用,还是推翻重来?
- SimpleFOC+PlatformIO踩坑之路
猜你喜欢
随机推荐
Multithreading and concurrency
【软件工程之美 - 专栏笔记】14 | 项目管理工具:一切管理问题,都应思考能否通过工具解决
#6898 变幻的矩阵 题解
IDEA安装scala
爬虫Requests库的一些简单用法
LeetCode #189.轮转数组
Hal library learning notes-13 application of I2C and SPI
新能源共享充电桩管理运营平台
Jingwei Qili: OLED character display based on hmep060 (and Fuxi project establishment demonstration)
FPGA based: multi-target motion detection (hand-in-hand teaching ①)
CV520国产替代Ci521 13.56MHz 非接触式读写器芯片
【软件工程之美 - 专栏笔记】26 | 持续交付:如何做到随时发布新版本到生产环境?
网络爬虫
NOI Online 2022普及组 题解&个人领悟
HR must ask questions - how to fight with HR (collected from FPGA Explorer)
封装——super关键字
传统模型预测控制轨迹跟踪——波浪形轨迹(功能包已经更新)
位运算学习笔记
LeetCode #19.删除链表的倒数第N个结点
Rowkey设计









