首页 > 解决方案 > 在不转换为字符串的情况下检查 int 是否为回文?

问题描述

public class Palindrome {
    public static void main(String args[]) {
        int x = 121;
        int res = 0;
        while (x > 0) {
            res = res * 10 + (x % 10);
            x /= 10;
        }
        if (x - res == 0) {
            System.out.println("True" + res);
        } else
            System.out.println("False" + res);
    }
}

你好!此代码用于检查整数是否为回文而不将 转换intString. 由于某种原因,计算机认为两者都代表数字res并不相同。感谢您的帮助,并提前感谢!x121

标签: javastringintpalindrome

解决方案


你很亲密。这是一个基于您所做的解决方案:

static bool isPalindrome (int n1, int n2) {
    return getReverseInteger(n1) == n2;
}

static int getReverseInteger (int n) {
    int nReversed = 0;
    while (n > 0) {
      int digit = n % 10;
      nReversed = nReversed * 10 + digit;
      n = (n - digit) / 10;
    }
    return nReversed;
}

推荐阅读