使用python实现回文数的四种方法小结
2019-12-11 12:11
1641 查看
回文数就是指整数倒过来和原整数相等。
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中使用多进程来实现并行处理的方法小结
- 四种apache禁止使用ip访问的实现方法
- python使用cStringIO实现临时内存文件访问的方法
- Python实现类的创建与使用方法示例
- python中getattr函数使用方法 getattr实现工厂模式
- python实现linux下使用xcopy的方法
- 计数排序的另一种实现(Python)附python中defaultdict方法的使用
- Python使用re实现str.strip()方法,去除首尾的空格
- 结合rpyc使用python实现动态升级的方法
- Python使用shelve模块实现简单数据存储的方法
- UI 动画之UIView动画的 四种 使用含有block的类方法 实现动画
- python判断字符串编码的简单实现方法(使用chardet)
- Python实现MySQL操作的方法小结【安装,连接,增删改查等】
- python使用threading获取线程函数返回值的实现方法
- python中的__new__方法与__init__方法区别与调用;通过使用__new__实现单例模式
- python实现的四种抽样方法
- python使用fileinput模块实现逐行读取文件的方法
- python使用smtplib模块通过gmail实现邮件发送的方法
- python使用reportlab实现图片转换成pdf的方法