[leetcode 9]Palindrome Number

1 题目:

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.

Show Tags
 
2 思路:
题设要求考虑负数,溢出问题。
我想的是获取整数位数,然后用头尾两个指针移动比较,这样不用考虑溢出。
 
题目要求的思路是,把这个数字回文一遍,然后比较。例如,1421回文为1241。但这样要考虑溢出,可以少除一位,然后比较余数。详情见代码。
 
3 代码:
我的思路:
    public boolean isPalindrome(int x) {
        if(x < 0){
            return false;
        }
        if(x == 0) return true;
        
        int len = 1;
        int temp = x;
        while( temp / 10 != 0){
            len++;
            temp = temp / 10;
        }
        
        int front = 1;
        int rear = len;
        temp = x;
        while(front < rear){
            int numFront = pow10(rear);
            int numRear = (front-1==0) ? temp%10 : temp/(pow10(front))%10;
            if(((temp/numFront)%10) != numRear){
                return false;
            }else{
                rear--;
                front++;
            }
        }
        return true;
    }
    
    public int pow10(int rank){
        int num = 10;
        rank = rank - 2;
        while(rank>0){
            num = num *10;
            rank--;
        }
        return num;
    }

别人思路代码:

public boolean isPalindrome(int x) {

    if (x < 0) return false;

    int p = x; 
    int q = 0; 

    while (p >= 10){
        q *=10; 
        q += p%10; 
        p /=10; 
    }

    return q == x / 10 && p == x % 10;
}
原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4559097.html