我有这个方法停留在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;
}
我运行你的代码,它工作正常; while循环退出。
您的代码中有2个错误:
.add(auxNum.divide)
电话中我假设你想要mod
而不是。==
。你必须使用.equals
(在while循环中使用.compareTo
工作正常,但.equals
更具可读性,因为它正确地表达了你想要完成的事情。你在最后,在return
中与==进行比较声明。应用这2个修复程序,您的代码正确返回true(对于回文)(十进制)数字,否则返回false。