9. Palindrome Number

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

思路:可以把从低位往高位挨个取得的余数,组成的数字跟原来数字比较是否相等。注意:1.负数不为Palindrome 2. 0 为Palindrome

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

也可以挨个比较第一位跟最后一位, 第二位跟倒数第二位,。。。。。

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) return false;
        if (x == 0) return true;
        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;
    }
}
Advertisements