回文数

作者: 张文超ai | 来源:发表于2019-07-19 18:36 被阅读0次
class Solution {



    public static boolean isPalindrome(int x) {

        //第一步 负数肯定不是回文数末位是0或者1到9也不是
        if(x<0||(x % 10 == 0 && x != 0)){
            return false;
        }

        //第二步 倒序之后超出Integer.MAX_VALUE,溢出的情况,抛异常


       int revertedNumber = 0;
        while (x > revertedNumber) {
            try{
                revertedNumber = revertedNumber * 10 + x % 10;
            }catch(Exception e){
                return false;
            }
            x /= 10;
        }
        return x == revertedNumber || x == revertedNumber / 10;

    }


}

2。

    class Solution {


    public static boolean isPalindrome(int x) {

        //第一步 负数肯定不是回文数末位是0或者1到9也不是
        if(x<0||(x % 10 == 0 && x != 0)){
            return false;
        }

        //第二步 倒序之后超出Integer.MAX_VALUE,溢出的情况,抛异常

        int before = x;
        int result = 0;
        while(x!=0){
            int pop = x%10;
            x = x/10;
            try{
                result = result * 10 + pop;
            }catch(Exception e){
                return false;
            }
        }
        return before == result;


    }


}

相关文章

网友评论

      本文标题:回文数

      本文链接:https://www.haomeiwen.com/subject/llaslctx.html