leetcode with python:9. Palindrome Number

题目:

Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.

前后开始读都一样的数字称为palindrome(ex:121),而题目要我们判断输入的X是否为palindrome

看到这题时我的想法

class Solution:    def isPalindrome(self, x: int) -> bool:        x=str(x)        for i in range(len(x)//2):            if x[i]!=x[-i-1]:                return False        return True 

转字串再从头尾开始比,一有不一样就return False,执行完都相同就return True
执行时间也来到58ms(faster than 94.92%)

正以为这题就要拉下帷幕时,发现题目下有一行

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

讨论区也不少人提出了不转字串的写法
于是我也尝试写了一个

class Solution:    def isPalindrome(self, x: int) -> bool:        if x<0:            return False        d=1        while x>=d*10:            d=d*10        while x:            if x//d!=x%10:                return False            x=(x%d)//10            d=d/100        return True

一开始负数绝对不会是palindrome所以直接回传False
先判断x是几位数
再透过%及//的操作来比较头尾
接着同样用%及//来去头去尾
头尾值不同就return False
整个执行完都相同就return True
最后执行时间135ms(faster than 11.45%)

虽然比较慢,但我觉得跟原本比起来算是很不一样的方法,所以分享一下

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章