3. Java- 回文数

package com.dhl.beyond;

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

public class 回文数 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(isPalindrome(-121));

    }
    public static boolean isPalindrome(int x) {
    
    
            if (x < 0) {
    
    
                return false;
            }
            if (reverse(x) == x) {
    
    
                return true;
            }
            return false;
        }

        public static int reverse(int x) {
    
    
            if (x == Integer.MIN_VALUE) return 0;
            int neg = x < 0 ? -1 : 1;
            x *= neg;
            int ret = 0;
            while (x > 0) {
    
    
                int n = ret;
                n *= 10;
                n += x % 10;
                x /= 10;
                if (n / 10 != ret) return 0;
                ret = n;
            }
            return ret * neg;
        }

}

方法二:

 public boolean isPalindrome(int x) {
    
    
        if (x < 0) {
    
    
            return false;
        }
        int help = 1;
        int tmp = x;
        while (tmp >= 10) {
    
    
            help *= 10;
            tmp /= 10;
        }
        while (x != 0) {
    
    
            if (x % 10 != x / help) {
    
    
                return false;
            }
            x = x % help / 10;
            help /= 100;
        }
        return true;
    }


猜你喜欢

转载自blog.csdn.net/Beyond_Nothing/article/details/114003560
今日推荐