【问题标题】:Checking whether an int is palindrome or not without converting into a string?在不转换为字符串的情况下检查 int 是否为回文?
【发布时间】:2019-03-15 23:59:25
【问题描述】:
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。提前感谢您的帮助和感谢!

【问题讨论】:

  • 它们不一样,你正在做 x/=10 改变 x,最后 x 将变为 0。
  • 计算机认为 res 与 x 不同,因为它们不是。 x 以 121 开始,循环之后为 0。
  • x - res == 0x == res 的一种写法:-)
  • 这只是一个粗略的代码,我已经多次重新排列每一行以查看导致错误的原因。我一直很迷信。

标签: java string int palindrome


【解决方案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;
}

【讨论】:

  • 即使您将其保留为 n=n/10 或者我错过了什么,它会起作用吗?
  • 不行,你需要减去 n % 10 的值。例如:121/10 = 12.1, 12.1/10 = 1.21, 1.21/10 = 0.21(即永远不会达到0)。
  • (121 - 1)/10 = 12, (12 - 2)/10 = 1, (1-1/10) = 0
  • 但是因为是int,所以它只需要12.1作为一个整数,也就是12。我猜我没看错
  • 是的,实际上你是对的。我在想浮动师。但如果 x 是一个 int,那么你每次都可以除以 10。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 2019-01-17
  • 1970-01-01
  • 2012-04-05
相关资源
最近更新 更多