【LeetCode】9. Palindrome Number Python3解法

本文介绍了一种不使用字符串转换的方法来判断一个整数是否为回文数。通过计算数字的位数,利用取余和乘以10的幂次方,实现了对输入整数的有效验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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.

Example 3:

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

思路:

比较暴力一点的就是转成string方法,不过这样很简单没什么意义。如果不用转换string方法,我们可以先计算这个数字的位数,然后通过取余并乘上10的位数减1次方。这样就可以计算出最后的结果。直接上代码!

代码:

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0: return False
        num = x
        check = x
        res = 0
        c = 0
        while x > 0:
            x = x // 10
            c += 1
        while num > 0:
            res += (num % 10) * (10**(c-1))
            num = num // 10
            c -= 1
        if res == check:
            return True
        else:
            return False

知识点:

求一个数的位数,一是转换成string然后用len()求,二就是这种方法。 c = 0 while x > 0: x = x // 10 c += 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值