[LeetCode] 9. Palindrome Number 验证回文数字

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?

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.

验证一个整数是否为回文,不能把整数变成字符,题目要求不能使用额外空间,也不能反转整数,因为可能会溢出。

可直接对整数进行取整和取余来获得想要的首尾数字,比如: 1221,取整1221 / 1000,可得首位1, 取余 1221 % 10, 可得到末尾1,进行比较,如果相等取中间的22继续用此方法比较。

Java:

public class Solution {
    public boolean intPalindrome(int num) {
        if (num < 0) return false;
        int div = 1;
        while ( num / div >= 10) div *= 10;
        while (num > 0) {
            int first = num / div;
            int last = num % 10;  
            if (first != last) return false;
            num = (num % div) / 10;
            div = div / 100;            
        }
         
        return true;
    }
}

Python: wo

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        div = 1
        while x / div >= 10:
            div *= 10
            
        while x > 0:
            first = x / div
            last = x % 10
            if first != last:
                return False
            x = (x % div) / 10
            div /= 100
            
        return True   

C++:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int div = 1;
        while (x / div >= 10) div *= 10;
        while (x > 0) {
            int left = x / div;
            int right = x % 10;
            if (left != right) return false;
            x = (x % div) / 10;
            div /= 100;
        }
        return true;
    }
};

  

类似题目:

[LeetCode] 125. Valid Palindrome 有效回文

[LeetCode] 5. Longest Palindromic Substring 最长回文子串

[LeetCode] 516. Longest Palindromic Subsequence 最长回文子序列

 

All LeetCode Questions List 题目汇总

  

  

posted @ 2018-03-02 14:22  轻风舞动  阅读(704)  评论(0编辑  收藏  举报