LeetCode之Easy篇 ——(9)Palindrome Number

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

思路一:颠倒整数,再比较。

import static java.lang.Math.abs;
class Solution {
    public boolean isPalindrome(int x) {
        int num = x;
        int res = 0;
        if(x<0){
            return false;
        }else{
            while(x!=0){
                if(abs(res) < Integer.MAX_VALUE / 10){
                        res = res * 10 + x % 10;
                        x /= 10;
                }else{
                    return false;//若翻转之后越界,肯定不是回文数。(输入值合法,翻转之后不合法,怎么可能相等!)
                }
            }
            return (res == num);   
        }
    }
}

思路二:翻转后半部分,与前半部分比较。

class Solution {
    public boolean isPalindrome(int x) {
        if(x <= 0 || x % 10 == 0) return false; //负数或者个位数为0
        int sum = 0;    //记录逆转的一半
        while(x > sum){
            sum = sum * 10 + x % 10;
            x /= 10;
        }
        return x == sum || x == sum / 10;    //包含数字位数是奇数和偶数的两种情况
    }
}

  

posted @ 2018-03-17 19:07  丶岑夫子  阅读(127)  评论(0编辑  收藏  举报