博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 9. Palindrome Number 解法 python
阅读量:2499 次
发布时间:2019-05-11

本文共 1365 字,大约阅读时间需要 4 分钟。

一.问题描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121Output: true

Example 2:

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

Example 3:

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

Follow up:

Coud you solve it without converting the integer to a string?

二.解题思路

首先负数肯定不是回文数,0`9这种个位的是回文数,其他情况的话就转成字符串判断头尾是否相等就好了

题目最后提到了能否用不转成字符串的方法解决

就是每次mod10求余数可以得到每个位置上的数,然后将数字反转

然后判定是否相等,相等就是回文数,不相等且反转后的数还小于待处理的数,则继续迭代

主要是要注意一下因为回文数有可能是偶数个位数,也有可能是奇数个位数

因此我们判断是否相等的时候得同时判断x和x/10

这x和反转数字更新不同步就会产生一个问题

对于像10,20,30....90这样的两位数10的倍数,除一次之后反转数字是0,更新后数字是9,判断x/10是否等于余数的时候,x/10也是0,解决的方法就是提前判断,可以发现能整除10的数都不是回文数,除了0,因为能整除10必定以0结尾,而0不能作为数字开头

附上两种实现方式

更多leetcode算法题解法请关注我的专栏或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

class Solution:    def isPalindrome(self, x: int) -> bool:        if x<0:return False        str_x=str(x)        if len(str_x)==1:return True        for t in range(int(len(str_x)/2)):            if str_x[t]!=str_x[-1-t]:                return False        return True
class Solution:    def isPalindrome(self, x: int) -> bool:        if x<0 or (x%10==0 and x!=0):return False        if x/10<1:return True        reverse_num=0        while reverse_num

 

转载地址:http://hqmrb.baihongyu.com/

你可能感兴趣的文章
Vue 路由懒加载根据根路由合并chunk块
查看>>
vue中 不更新视图 四种解决方法
查看>>
MySQL 查看执行计划
查看>>
OpenGL ES 3.0(四)图元、VBO、VAO
查看>>
OpenGL ES 3.0(五)纹理
查看>>
OpenGL ES 3.0(八)实现带水印的相机预览功能
查看>>
OpenGL ES 3.0(九)实现美颜相机功能
查看>>
FFmpeg 的介绍与使用
查看>>
Android 虚拟机简单介绍——ART、Dalvik、启动流程分析
查看>>
原理性地理解 Java 泛型中的 extends、super 及 Kotlin 的协变、逆变
查看>>
FFmpeg 是如何实现多态的?
查看>>
FFmpeg 源码分析 - avcodec_send_packet 和 avcodec_receive_frame
查看>>
FFmpeg 新旧版本编码 API 的区别
查看>>
RecyclerView 源码深入解析——绘制流程、缓存机制、动画等
查看>>
Android 面试题整理总结(一)Java 基础
查看>>
Android 面试题整理总结(二)Java 集合
查看>>
学习笔记_vnpy实战培训day02
查看>>
学习笔记_vnpy实战培训day03
查看>>
VNPY- VnTrader基本使用
查看>>
VNPY - CTA策略模块策略开发
查看>>