程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetcode 9 Palindrome Number 回文數

leetcode 9 Palindrome Number 回文數

編輯:C++入門知識

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]

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved