为什么在循环退出时没有compareTo BigInteger?

问题描述 投票:0回答:1

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

    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;
}
java while-loop biginteger
1个回答
3
投票

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

您的代码中有2个错误:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.