冒着让这个问题被投票为重复,甚至被关闭的风险,我提出了这个问题。
背景
在 int、long long 等“普通”数据类型中,要将二进制数值转换为十进制字符串,您需要执行以下操作(在伪代码中):
Set length = 0
Set divisor to largest base10 value the data type will hold (Divisor).
Loop
Divide number in question by divisor.
Place result in a string at position length.
Increment the length by 1.
Divide the divisor by 10.
Reverse the string.
Print the string.
(大多数)任何语言的实际实现都是微不足道的。
问题
我在上述方法中遇到的问题是,对于大整数(也称为任意精度算术),没有最大的以 10 为底的值开始。所以问题是“如果无法知道那个值是什么,你如何将除数初始化为最大可能的 base10 值?”
我试过的
仍在尝试起草解决方案。
研究
我在这里找到的一些链接包括以下内容:
将“大”十六进制数(字符串格式)转换为没有 BigInteger 类的十进制数(字符串格式)
将 BigInteger 转换为十进制(Base 10)字符串的最快方法?
将“大”十六进制数(字符串格式)转换为没有 BigInteger 类的十进制数(字符串格式)
谷歌搜索发现了其他东西,但没有什么能具体回答我的问题。
想法
我认为可能有效的一种方法如下(在伪代码中):
Define p_divisor as previous divisor.
Set divisor = 1
Loop:
if divisor < dividend
then
Set p_divisor = divisor
divisor = divisor * 10
else
end loop
Loop:
Divide number in question by divisor.
Place result in a string at position length.
Increment the length by 1.
Divide the divisor by 10.
if divisor == 1 then end loop
Reverse the string.
Print the string.
这是正确的方法吗?我有一个大型整数库正在运行(包括乘法和除法),因此实现它并不难。我看到这种方法的最大问题是性能,因为你必须运行一个乘法序列来获得初始除数,然后你必须为每个 base10 位置除以两次。一个用于实际除法,另一个用于除数。