Palindrome Number 回文数

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

判断一个数是否为回文数。我们需要知道的负数不属于回文数。可以有很多种思路解决这道题。可以把这个整数转换成字符串,然后用双指针进行比较;也可以将这个整数反转,然后对比反转后是否和原来的数相同。第一种方法不用考虑整数越界问题,用第二种方法的时候要注意越界问题。下面是两个方法的代码:

1,转成字符串
public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        String s = String.valueOf(x);
        int l = 0;
        int r = s.length() - 1;
        while(l < r) {
            if(s.charAt(l) != s.charAt(r))
                return false;
            l ++;
            r --;
        }
        return true;
    }
}


2,整数反转
public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int result = 0;
        int ox = x;
        while(x != 0) {
            if(result > (Integer.MAX_VALUE - x % 10) /10)
                return false;
            result = result * 10 + x % 10;
            x /= 10;
        }
        return result == ox;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2273554