Leetcode 9. Palindrome Number

Leetcode 9. Palindrome Number

题目说明

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

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.

代码部分1

class Solution:
    def isPalindrome(self, x: 'int') -> 'bool':
        out = False
        if x < 0:
            return out
        xrev = str(x)
        rev = xrev[::-1]
        if xrev == rev:
            out = True
        return out

Runtime: 240 ms, faster than 86.76% of Python3 online submissions for Palindrome Number.

Memory Usage: 12.7 MB, less than 89.14% of Python3 online submissions for Palindrome Number.

后续在想不可能啊,题目怎么会这个简单
emmm果然有后续
Coud you solve it without converting the integer to a string?

代码部分2

class Solution:
    def isPalindrome(self, x: 'int') -> 'bool':
        if x < 0:
            return False

        ranger = 1
        while x / ranger >= 10:
            ranger *= 10

        while x:
            left = x // ranger
            right = x % 10
            if left != right:
                return False
            
            x = (x % ranger) // 10
            ranger //= 100

        return True

Runtime: 248 ms, faster than 78.29% of Python3 online submissions for Palindrome Number.

Memory Usage: 13.5 MB, less than 5.03% of Python3 online submissions for Palindrome Number.

思路解析:
ranger用于寻找最高位:
while x:
left代表此时左边最高位
right代表此时右边最低位
比较left与right:若成功 则继续比较接下来的位置,否则返回false
x对ranger取余(去除最高位);对10向下取整(去除最低位)
ranger降两位
循环,比较次高位与次低位

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值