leetcode 9.回文数

方法一

/*
思路:先把整数反转(参考第七题),再判断是否相同
* */

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

方法二

/*
思路:把整数转换为字符串,用reverse()进行翻转
      将翻转后的字符串与原字符串比较
* */

class Solution {
    public boolean isPalindrome(int x){
        String str = new StringBuilder(x+"").reverse().toString();
        return str.equals(x+"");
    }
}

 

你可能感兴趣的:(leetcode)