[LeetCode]#9 回文数

时间:2021-07-16
本文章向大家介绍[LeetCode]#9 回文数,主要包括[LeetCode]#9 回文数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

输入:x = 121

输出:true

这不就是之前做过的整数反转吗 (详情见链接:https://www.cnblogs.com/jpppp/p/15016573.html

同样有两种解法,数学解法和字符串解法。

解法一

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

解法二

class Solution {
    public boolean isPalindrome(int x) {

        try{
            String s = String.valueOf(x);
            String res = new StringBuffer(s).reverse().toString();
            int res_i = 0;
            if(x >= 0){
                res_i = Integer.parseInt(res)<Integer.MIN_VALUE||Integer.parseInt(res)>Integer.MAX_VALUE?0:(int)Integer.parseInt(res);
            } else {
                res_i = -Integer.parseInt(res.substring(0,res.length()-1))<Integer.MIN_VALUE||-Integer.parseInt(res.substring(0,res.length()-1))>Integer.MAX_VALUE?0:(int)-Integer.parseInt(res.substring(0,res.length()-1));
            }
            if(x < 0) return false;
            if(res_i == x) return true;
            return false;
        }catch(Exception e){
            return false;
        }
        
    }

}

总结:完全一样,总结个屁

原文地址:https://www.cnblogs.com/jpppp/p/15020824.html