java - 为什么 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;
}
解决方案
我运行了你的代码,它工作正常;while 循环退出。
您的代码确实有 2 个错误:
- 在
.add(auxNum.divide)
通话中,我假设您想要mod
。 - 您无法将 bigints 与
==
. 您必须使用.equals
( 在您使用的 while 循环中,.compareTo
它工作正常,但.equals
更具可读性,因为它正确地表达了您要完成的工作。您在return
语句的最后与 == 进行比较。
应用这 2 个修复程序,您的代码对于回文(十进制)数字正确返回 true,否则返回 false。
推荐阅读
- discord.py - 如何获取在 discord.py rewrite 中做出反应的所有用户的列表
- javascript - State Redux 没有映射到 props
- java - 在 Javafx 中对齐两个滚动网格窗格
- javascript - 正则表达式用于逗号与换行符之间的对 Javascript
- python - 为什么 python 会混淆我的模块包
- google-apps-script - 如何将附加到工作表的 Google 应用脚本有选择地分发给不属于同一 G Suite 域的人员
- java - 使用 JUnit/Mockito 模拟保存方法
- sql-server - 在 VS Code 中构建 SQL Server 项目
- css - Angular CSS 布局应用但没有结果
- node.js - 为什么在 Google Classroom API 上创建课程不起作用?