回文数Python解法
生活随笔
收集整理的这篇文章主要介绍了
回文数Python解法
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
例:
输入:x = 121
输出:true
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
# 1 双指针。两个指针指向中心,然后像两端遍历。
class Solution:def isPalindrome(self, x: int) -> bool:if x < 0:return Falses = str(x)length = len(s)left, right = 0, 0if length & 1 == 1:left, right = int(length//2), int(length//2)else:left, right = int(length/2-1), int(length/2)while left >= 0 and right < length:if left == 0 and right == length - 1:if s[left] == s[right]:return Trueif s[left] != s[right]:return Falseleft -= 1right += 1# 2 直接Python正反遍历即可:若正反遍历相同则代表是回文数
class Solution(object):def isPalindrome(self, x):""":type x: int:rtype: bool"""return x>-1 and str(x)[::-1]==str(x)# 3 在不将整数转换成字符串的情况下解决。使用除余。
class Solution(object):def isPalindrome(self, x):""":type x: int:rtype: bool"""if x < 0:return Falseyu, y, x2 = 0, 0, x # 余数,翻转后的结果,当前xwhile x2 != 0:yu = x2%10 # 求余y = y*10 + yu # 计算翻转x2 = x2//10 # x右移一位return y==x总结
以上是生活随笔为你收集整理的回文数Python解法的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 推进人体实验 马斯克脑机接口公司开始寻找
- 下一篇: 整数转罗马数字Python解法