java BigInteger:计算可伸缩方法中的小数位数
我需要一个BigInteger
的十进制数字计数。例如:
99
返回2
1234
返回4
9999
返回4
12345678901234567890
返回20
我需要对一个BigInteger
有184948
个十进制数字和更多的的BigInteger
执行此操作如何快速且可扩展地执行此操作强>
转换为字符串的方法很慢:
public String getWritableNumber(BigInteger number) {
// Takes over 30 seconds for 184948 decimal digits
return "10^" + (number.toString().length() - 1);
}
这种十次循环的方法甚至更慢:
public String getWritableNumber(BigInteger number) {
int digitSize = 0;
while (!number.equals(BigInteger.ZERO)) {
number = number.divide(BigInteger.TEN);
digitSize++;
}
return "10^" + (digitSize - 1);
}
有没有更快的方法
# 1 楼答案
这是比转换为字符串方法更快的另一种方法。虽然不是最佳运行时间,但仍然是合理的0.65秒,而使用Convert to String方法时为2.46秒(180000位)
此方法根据给定值计算以10为底对数的整数部分。然而,它没有使用循环除法,而是使用了一种类似于平方求幂的技术
下面是实现前面提到的运行时的粗略实现:
希望这会有所帮助
# 2 楼答案
下面是一个基于Dariusz's answer的快速方法:
以下代码测试数字1、9、10、99、100、999、1000等,一直测试到一万位:
这可以检查
BigInteger
和184,948
十进制数字,以及一秒以内的更多数字# 3 楼答案
您可以首先将
BigInteger
转换为BigDecimal
,然后使用这个answer来计算位数。这似乎比使用BigInteger.toString()
更有效,因为这将为String
表示分配内存# 4 楼答案
这看起来很有效。我还没有运行详尽的测试,也没有运行任何时间测试,但它似乎有一个合理的运行时间
在我的Celeron M笔记本电脑上花了大约3秒,所以在一些像样的装备上应该会达到2秒以下
# 5 楼答案
我认为可以使用bitLength()获得log2值,然后使用change the base to 10
结果可能是错误的,但是,一个数字,所以这只是一个近似值
但是,如果这是可以接受的,您可以始终将1添加到结果中,并将其绑定为最多。或者,减去1,得到至少