冒险让这个问题被投票为重复,甚至可能被关闭,我仍然想问一下这个问题。
背景
在“普通”的数据类型中,比如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值?”
我尝试过的方法
仍在尝试起草解决方案。
研究
我找到的一些链接包括以下内容:
将“大”十六进制数字(字符串格式)转换为十进制数字(字符串格式),而不使用BigInteger类
{{link2:C:以十进制打印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.
这样做是否正确?我已经有一个大整数库(包括乘法和除法)正在运作,所以很容易完成。我看到这种方法的主要问题是性能,因为您必须运行乘法序列以获取初始除数,然后对每个十进制位进行两次除法。一次是实际的除法,另一次是除数。
p_divisor = divisor
,然后将divisor
乘以10会导致无论使用什么整数类型都会溢出。 - chux - Reinstate Monica