卖萌的弱渣

I am stupid, I am hungry.

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.

Solution

  • 把x反转,除了最高位不要.
  • p是反转以后的结果,q是最高位

  • Java Solution:

(Palindrome-Number.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
    public boolean isPalindrome(int x) {
        if (x<0) return false;
        int p = x;
        int q = 0;
        // q是x的反转版本,除了最高位,因为怕overflow
        while (p>=10){
            q = 10*q + p%10;
            p = p/10;
        }
        return (q==x/10) && (p == x%10);
    }
}
(Palindrome-Number.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0 :
            return False
        tmp = x
        num = 0
        # 确定位数
        while tmp/10 != 0:
            tmp =tmp/10
            num += 1
        # 个位数永远都是
        if num == 0:
            return True

        y = x
        # x从最高位,y从个位
        while y != 0 and x != 0:
            if x/(10**num) != y%10:
                return False
            x = x%(10**num)
            y = y/10
            num = num-1
        return True