第七题,isPalindrome

Question:

求是否是回文,顾名思义就是返过来也是相同的数。

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.

Follow up:

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

Code:

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if list(str(x))[::-1] == list(str(x)):
            return True
        else:
            return False
    def isPalindrome2(self,x):
        if x < 0 or (x % 10 == 0 and x != 0):
            return False

        reverted_number = 0
        while x > reverted_number:
            reverted_number = reverted_number * 10 + x % 10
            x = int(x/10)

        return x == reverted_number or x == int(reverted_number / 10)

s = Solution()
print("The first method:")
print(s.isPalindrome(121))
print(s.isPalindrome(-121))
print(s.isPalindrome(10))
print(s.isPalindrome(11))
print("The second method:")
print(s.isPalindrome2(121))
print(s.isPalindrome2(-121))
print(s.isPalindrome2(10))
print(s.isPalindrome2(11))

Result:

The first method:
True
False
False
True
The second method:
True
False
False
True

 

 

第一个方法是通过int转str,再转list,再颠倒一下list。这个方法题目中有提到不可用。

第二个方法就是类似于第六题中,反转方法,负数一律不是回文。对于正数,如果后半段反转得到的是和剩下前半段一样就说明是回文。

那么什么时候判断是一半呢,就是前半段已经小于后半段时,就反转了一半了。

如果长度是偶数,那么前一半和后一半的反转是一样的,如果长度是奇数,那么前一半和后一半(多出一位)除以10是一样的。既不看中间那位,前后是一样的。

第二个方法复杂度:

  • Time complexity : O(log10​(n)). We divided the input by 10 for every iteration, so the time complexity isO(log10​(n))

  • Space complexity : O(1).

转载于:https://my.oschina.net/u/3784241/blog/3002970

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值