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

yipeiwu_com6年前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设计】。

相关文章

Django自定义插件实现网站登录验证码功能

Django自定义插件实现网站登录验证码功能

前言 网站登录的时候我们常常会看到随机的验证码需要输入后台验证,如图: 现在我们来实现在Django中通过自定制插件来实现随机验证 check_code.py 基于PIL生成一个带验证...

python2.7和NLTK安装详细教程

本文为大家分享了python2.7和NLTK安装教程,具体内容如下 系统:Windows 7 Ultimate 64-bits Python 2.7安装 下载Python 2.7:官网下...

详解Python3.6的py文件打包生成exe

详解Python3.6的py文件打包生成exe

原文提到的要点: 1. Python版本32位 (文件名为 python-3.6.1.exe) 2. 安装所有用到的模块(原文博主用的是openpyxl,我用到的有urllib中的req...

在Python中调用Ping命令,批量IP的方法

如下所示: #!/usr/bin/env python #coding:UTF-8 ''''''' Author: jefferchen@163.com 可在命令行直接带目的IP...

Python and、or以及and-or语法总结

一、and: 在Python 中,and 和 or 执行布尔逻辑演算,如你所期待的一样,但是它们并不返回布尔值;而是,返回它们实际进行比较的值之一。 复制代码 代码如下: >>...