zoukankan      html  css  js  c++  java
  • 【leetcode】Palindrome Number

    题目简述:

    Determine whether an integer is a palindrome. Do this without extra space.
    Some hints:
    Could negative integers be palindromes? (ie, -1)

    If you are thinking of converting the integer to string, note the restriction of using extra space.

    You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

    There is a more generic way of solving this problem.

    解题思路:

    首先最简单的就是想到直接转成字符串最前一个和最后一个比较,而且做出来效果还不错。不过题目说可以直接操作数字,那么我们也可以想办法每次取出数字的最高位和最低位进行比较,办法就是用一个base取最高位,每次取后base/100

    class Solution:
        # @return a boolean
        def isPalindrome(self, x):
            if x < 0:
                return False
            else:
                s = str(x)
            l = len(s)
            for i in range(l/2):
                if s[i] != s[l-i-1]:
                    return False
            return True
    
    class Solution:
        # @return a boolean
        def isPalindrome(self, x):
            if x < 0:
                return False
            base = 1
            while x / base >= 10:
                base *= 10
            while  x > 0:
                left = x / base
                right = x % 10
                if left != right:
                    return False
                x -= base * left
                x /= 10
                base /= 100
            return True
  • 相关阅读:
    Oracle面试题及答案整理
    Oracle问题总结
    Dubbo(四) -- telnet命令
    Dubbo(三) -- 多协议支持与多注册中心
    每天一算法 -- (冒泡排序)
    Dubbo(二) -- Simple Monitor
    数据库优化
    ActiveMQ内存配置和密码设置
    Dubbo源码导入Eclipse遇到的问题
    Dubbo(一) -- 初体验
  • 原文地址:https://www.cnblogs.com/MrLJC/p/4241780.html
Copyright © 2011-2022 走看看