如果没有转换为字符串,检查int是否是回文?

问题描述 投票:1回答:1
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);
    }
}

你好!此代码用于检查整数是否为回文,而不将int转换为String。出于某种原因,计算机认为resx不同,尽管两者都代表121。感谢您的帮助,并提前致谢!

java string int palindrome
1个回答
1
投票

你很亲密以下是基于您所做的解决方案:

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.