Leetcode算法——9、回文整数

76 篇文章 1 订阅

题目

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

判断一个整数是否是一个回文数(后往前读与从前往后读一样)

示例:

Input: 121
Output: true
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.
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

思路

1、递归法

实现一个递归函数,每次比较一个数的最高位和最低位是否相等,然后去掉最高位和最低位,继续判断。
设整数位数位n,则计算位数的时间复杂度为 O(n),递归的时间复杂度为 O(n),因此整体时间复杂度为 O(2n)。

2、反转法

对整数反转一半,然后与另一半对比是否相等。时间复杂度为 O(n/2)。

虽然严格来说两个方法的时间复杂度都为 O(n),但是系数相差了4倍。

python实现

def isPalindrome(x):
    """
    :type x: int
    :rtype: bool
    """
    
    def fun_rec(x, length):
        '''
        递归函数,判断x是否是回文数
        length:x的长度
        '''
        
        # 递归结束条件
        if length <= 1:
            return True
        
        # 比较最低位和最高位
        low = x % 10
        up = int(x / (10 ** (length - 1)))
        if low == up:
            x = int((x - low - up * (10 ** (length - 1))) / 10)
            return fun_rec(x, length - 2)
        return False
    
    # 边界条件
    if x < 0:
        return False
    
    # 判断x的长度
    length = 1
    while(x / (10 ** length) >= 1):
        length += 1
        
    return fun_rec(x, length)


def isPalindrome2(x):
    """
    :type x: int
    :rtype: bool
    对x反转一半,然后与另一半对比是否相等
    """
    
    if x < 0 or (x > 0 and x % 10 == 0):
        return False
    
    revert = 0
    while(x > revert):
        revert = revert * 10 + x % 10
        x = int(x / 10)
    
    return x == revert or x == int(revert / 10)
    
if '__main__' == __name__:
    x = 1001
    print(isPalindrome(x))
    print(isPalindrome2(x))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值