使用python实现回文数的四种方法小结

作者:求兵 时间:2022-01-17 14:57:51 

回文数就是指整数倒过来和原整数相等。


Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

1:整数转字符串,通过下标对比确定该整数是否为回文数


str_x = str(x)
for i in range(0,int(len(str_x)/2)):
 if str_x[i] != str_x[-i-1]:
   return False
return True

2:字符串切片操作,str[index:index:step],中括号里面分别为:字符起点、终点和步长


str_x = str(x)
return str_x == str_x[::-1]

3:数学计算的方法,对比反转整数的值


if x<0:
 return False
temp_x = x;
palindromeNum = 0
while temp_x != 0:
 palindromeNum = palindromeNum*10 + temp_x%10
 temp_x /= 10
return palindromeNum == x

4:整数转字符串,反转字符串,对比反转后字符串与原字符串是否相等


str_x = str(x)
str_y = ""
for i in str_x:
 str_y = i + str_y
return str_y == str_x

来源:https://blog.csdn.net/qiubingcsdn/article/details/81773168

标签:python,回文数
0
投稿

猜你喜欢

  • 如何在ASP里面创建GUID

    2008-01-08 19:13:00
  • Python的MongoDB模块PyMongo操作方法集锦

    2021-02-05 17:59:03
  • 基于JS判断iframe是否加载成功的方法(多种浏览器)

    2023-08-24 04:14:52
  • 详解python pandas 分组统计的方法

    2021-01-30 05:33:48
  • Python+OpenCV内置方法实现行人检测

    2023-10-19 12:52:47
  • 人工神经网络算法知识点总结

    2023-05-16 11:36:06
  • 6个asp判断函数使用方法介绍

    2007-09-24 13:10:00
  • IE及Opera浏览器兼容笔记

    2008-08-21 17:53:00
  • SQLServer 连接 EXCEL

    2009-07-09 19:00:00
  • 通过Pandas读取大文件的实例

    2023-12-25 21:18:31
  • SQL Server中两种修改对象所有者的方法

    2009-01-15 13:10:00
  • 使用pandas的DataFrame的plot方法绘制图像的实例

    2023-07-02 08:33:52
  • 人工智能——K-Means聚类算法及Python实现

    2022-02-04 19:04:43
  • 如何让shell终端和goland控制台输出彩色的文字

    2023-07-13 03:24:56
  • php之app消息推送案例教程

    2023-06-15 00:42:02
  • spyder快捷键与python符号化输出方式

    2023-08-23 11:58:24
  • 几个图片按比例缩放的代码

    2008-02-13 08:51:00
  • XML 在使用中产生的二十个热点问题

    2008-05-29 11:07:00
  • Python深度优先算法生成迷宫

    2023-05-13 08:38:09
  • 仿豆瓣分页原型(Javascript版)

    2007-11-05 14:04:00
  • asp之家 网络编程 m.aspxhome.com