zoukankan      html  css  js  c++  java
  • leetcode 9 Palindrome Number 回文数

    Determine whether an integer is a palindrome. Do this without extra space.

    click to show spoilers.

    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.

    非常简洁的c++解决方案:
    对于回文数只比较一半

    public boolean isPalindrome1(int x) {
        if (x == 0) return true;
        // in leetcode, negative numbers and numbers with ending zeros
        // are not palindrome
        if (x < 0 || x % 10 == 0)
            return false;
    
        // reverse half of the number
        // the exit condition is y >= x
        // so that overflow is avoided.
        int y = 0;
        while (y < x) {
            y = y * 10 + (x % 10);
            if (x == y)  // to check numbers with odd digits
                return true;
            x /= 10;
        }
        return x == y; // to check numbers with even digits
    }
    

    python这个解法应该是前后分别对比:

    
    class Solution:
        # @param x, an integer
        # @return a boolean
        def isPalindrome(self, x):
            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
    
    

    python字符串的解法:

    class Solution:
        # @param {integer} x
        # @return {boolean}
        def isPalindrome(self, x):
            return str(x)==str(x)[::-1]
    
  • 相关阅读:
    通过Asp.Net MVC的区域功能实现将多个MVC项目部署
    对初步创业的软件企业的思考
    白色恋人
    ASP.NET中动态控制RDLC报表
    什么时候该用委托,为什么要用委托,委托有什么好处....
    asp.net mvc 3
    Salesforce多租户架构
    很有用的系统命令和一些技巧
    产品设计
    RDLC报表部署及MVC部署 所需dll
  • 原文地址:https://www.cnblogs.com/wuyida/p/6301322.html
Copyright © 2011-2022 走看看