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

yipeiwu_com5年前Python基础

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

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

以上这篇使用python实现回文数的四种方法小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python线性拟合实现函数与用法示例

Python线性拟合实现函数与用法示例

本文实例讲述了Python线性拟合实现函数与用法。分享给大家供大家参考,具体如下: 1. 参考别人写的: #-*- coding:utf-8 -*- import math impo...

python画图--输出指定像素点的颜色值方法

如下所示: # -*- coding: utf-8 -*- #------------------------------------------------------------...

Python实现读取目录所有文件的文件名并保存到txt文件代码

代码: (使用os.listdir) 复制代码 代码如下: import os def ListFilesToTxt(dir,file,wildcard,recursion): &nb...

django 数据库连接模块解析及简单长连接改造方法

工作中纯服务端的项目用到了线程池和django的ORM部分。django 的数据库连接在每一个线程中开启一份,并在查询完毕后自动关闭连接。 线程池处理任务时,正常使用的连接中不会被关闭,...

python 视频逐帧保存为图片的完整实例

我就废话不多说了,直接上代码吧! import cv2 import os def save_img(): video_path = r'F:\test\video1/' v...