[Leetcode] 9. Palindrome Number

2017-12-19  本文已影响0人  lijia069

Related Topics:[Math]
Similar Questions:[Palindrome Linked List]

题目: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.

思路

  1. 可以从数字两头出发,进行比较;
  2. 将数字分成两部分,将左半部分和右半部分的颠倒进行比较。

java解法1:

class Solution {
    public boolean isPalindrome(int x) {
        //从两头出发
        if(x<0) return false;
        int div=1,left,right;
        //求最高位的除数
        while(x/div>=10) div*=10;
        while(x>0) {
            left=x/div;
            right=x%10;
            if(left!=right) return false;
            x=(x%div)/10;
            div/=100;
        }
        return true;
    }
}

java解法2:

class Solution {
    public boolean isPalindrome(int x) {       
        //将x分成左右两部分比较
        //负数、以及10的倍数 返回false
        if(x<0||x!=0&&x%10==0) return false;
        int res=0;
        while(res<x) {
            res=res*10+x%10;
            x=x/10;
        }
        return(x==res||x==res/10);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读