Palindrome Number, Leetcode 解题笔记

Determine whether an integer is a palindrome. Do this without extra space.

这道题可以利用之前的Reverse Integer的解法,先翻转x,在对比是否与原x一致。注意x<0时,返回false。

public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int r = reverse(x);
        if(r == x) return true;
        else return false;
    }
    public int reverse(int x) {
        int ret = 0;
        int last = 0;
        while(x != 0){
            last = x % 10;
            x = x / 10;
            ret = ret*10 + last;
        }
        return ret;
    }
}

这道题的另一解法是直接从两头取digit比较,如果一致,向内继续比较,如果不一致,返回false。

public class Solution {
    public boolean isPalindrome(int x) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int num = x;
        int counter = 0;
        int front = 0;
        int end = 0;
        boolean result = false;

        if(x < 0){
            return false;
        }

        while(num >= 10){
            num = num/10;
            counter++;
        }

        num = x;
        while(num > 10){
            end = num%10;
            front = num/((int)Math.pow(10, counter));
            if(end != front){
                break;
            }
            num = num/10;
            num = num - front*((int)Math.pow(10, counter));
            counter--;
        }
        if(num < 10)
            result = true;
        return result;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s