当前位置:网站首页>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)还可以考虑回文因为是对称的,其实可以不用全部反转后对比,而是从中间分开,前后对比。
此处不想再写了。
边栏推荐
猜你喜欢

【软件工程之美 - 专栏笔记】30 | 用好源代码管理工具,让你的协作更高效

ABSA1: Attentional Encoder Network for Targeted Sentiment Classification

【软件工程之美 - 专栏笔记】22 | 如何为项目做好技术选型?

Based on stc51: schematic diagram and source code of four axis flight control open source project (entry-level DIY)

STM32 MDK(Keil5) Contents mismatch错误总结

多线程和并发

CS4344国产替代DP4344 192K 双通道 24 位 DA 转换器

物联网倾斜监测解决方案

智慧能源管理系统解决方案

【软件工程之美 - 专栏笔记】27 | 软件工程师的核心竞争力是什么?(上)
随机推荐
Hal library learning notes - 9 DMA
【软件工程之美 - 专栏笔记】22 | 如何为项目做好技术选型?
Power electronics: single inverter design (matlab program +ad schematic diagram)
【软件工程之美 - 专栏笔记】“一问一答”第3期 | 18个软件开发常见问题解决策略
八大排序----------------冒泡排序
【RoboMaster】A板接收JY-ME01角度传感器数据--modebus协议&CRC软件校验
太原市公交路线爬取
Zero basics FPGA (5): counter of sequential logic circuit design (with introduction to breathing lamp experiment and simple combinational logic design)
FPGA based: multi-target motion detection (hand-in-hand teaching ①)
【软件工程之美 - 专栏笔记】14 | 项目管理工具:一切管理问题,都应思考能否通过工具解决
SimpleFOC+PlatformIO踩坑之路
2022暑初二信息竞赛学习成果分享2
物联网倾斜监测解决方案
【软件工程之美 - 专栏笔记】26 | 持续交付:如何做到随时发布新版本到生产环境?
Logistic regression - project practice - credit card detection task (Part 2)
Huawei cloud 14 days Hongmeng device development -day1 environment construction
From entry to soul: how to use tb6600 single chip microcomputer to control stepping motor with high precision (42/57)
关于时间复杂度的个人看法
Ml8 self study notes
【软件工程之美 - 专栏笔记】17 | 需求分析到底要分析什么?怎么分析?