首页 > 解决方案 > 为什么 compareTo BigInteger while 循环不退出?

问题描述

我有这个方法卡在一个while循环中,我在方法本身中打印条件的布尔值,它最终会变为假,但它不会退出循环。

    public static boolean isPalindrome(BigInteger num) {
         BigInteger invertedNum = BigInteger.valueOf(0);
         BigInteger auxNum = num;

         while (auxNum.compareTo(BigInteger.valueOf(0)) != 0) {
             invertedNum = invertedNum.multiply(BigInteger.valueOf(10)).add(auxNum.divide(BigInteger.valueOf(10)));
             auxNum = auxNum.divide(BigInteger.valueOf(10));
             System.out.println(auxNum.compareTo(BigInteger.valueOf(0)) != 0);
    }

    return invertedNum == num;
}

标签: javawhile-loopbiginteger

解决方案


我运行了你的代码,它工作正常;while 循环退出。

您的代码确实有 2 个错误:

  • .add(auxNum.divide)通话中,我假设您想要mod
  • 您无法将 bigints 与==. 您必须使用.equals( 在您使用的 while 循环中,.compareTo它工作正常,但.equals更具可读性,因为它正确地表达了您要完成的工作。您在return语句的最后与 == 进行比较。

应用这 2 个修复程序,您的代码对于回文(十进制)数字正确返回 true,否则返回 false。


推荐阅读