假设您没有任意精度的数学包可供使用,但您确实有
一组基本的字符串操作例程,您可以执行以下操作:
构造一个2的幂列表,然后反向解构二进制字符串
通过为字符串中的每个“1”位添加适当的 2 次方,一次订购一位。
您需要执行此操作的唯一任意精度算术函数是加法,这是相当公平的
使用长手算术很容易实现。
假设您确实实现了一个名为的任意算术加法函数:
ADD 将 2 个包含十进制数字的字符串作为输入并返回十进制和
作为一个字符串。比如:
SumString = ADD(DecimalString1, DecimalString2)
SumString 是一串十进制数字,表示DecimalString1 和DecimalString2 之和。
Step1:构造一个 2 的幂列表,如下所示:
BitString is string /* String of '1' and '0' values... */
BitString = '111001101001110100100(...)1001001111011100100' /* or whatever... */
PowerOf2 is array of string /* Array of strings containing powers of 2 */
PowerOf2[1] = '1' /* 2**0 to get things started... */
/* Build as many powers of 2 as there are 'bits' in the input string */
for i from 2 to length(BitString) by +1
PowerOf2[i] = ADD(PowerOf2[i-1], PowerOf2[i-1])
end
注意:以上假设数组/字符串是从 1 开始的(而不是从零开始的)。
第 2 步:解构 BitString,不断累积总和:
DecimalValue is string /* Decimal value of BitString */
BitString is string /* Your input set of bits as a string... */
ReverseBitString is string /* Reversed input */
DecimalValue = '' /* Result */
BitString = '111001101001110100100(...)1001001111011100100' /* or whatever... */
ReverseBitString = reverse(BitString) /* Reverse so we process lsb to msb */
for i from 1 to length(ReverseBitString) by +1
if substr(ReverseBitString, i, 1) == '1' then /* Bit at position i */
DecimalValue = ADD(DecimalValue, PowerOf2[i])
end
end
if DecimalValue = '' then DecimalValue = '0' /* bit string was all zero */
Display DecimalValue /* This is the result */
如何构建任意精度的ADD函数?它是这样的:
function ADD (DecVal1 is string, DecVal2 is string) return string
SumVal is string
Rev1 is string
Rev2 is string
DigitSum is integer
CarryDigit is integer
SumVal = '' /* Result so far... */
Rev1 = reverse(DecVal1) /* Reverse digit order */
Rev2 = reverse(DecVal2) /* Reverse digit order */
/* Pad shorter reversed sting with trailing zeros... */
if length(Rev1) > length(Rev2) then
Rev2 = concat(Rev2, copies(length(Rev1) - length(Rev2), '0')
end
else
Rev1 = concat(Rev1, copies(length(Rev2) - length(Rev1), '0')
end
/* Sum by digit position, least to most significant */
CarryDigit = 0
for i from 1 to length(Rev1) by + 1
DigitSum = CtoI(substr(Rev1, i, 1)) + CtoI(substr(Rev2, i, 1)) + CarryDigit
if DigitSum > 9 then
DigitSum = DigitSum - 10
CarryDigit = 1
end
else
CarryDigit = 0
end
SumVal = concat(ItoC(DigitSum), SumVal)
end
if CarryDigit > 0 then
SumVal = concat(ItoC(CarryDigit), SumVal)
end
return SumVal
假设内置字符串函数:
- reverse(String):逆序返回字符串
- length(String):返回给定字符串的长度
- concat(String, String):返回两个字符串的串联
- substr(String, start, length):从 start 处返回字符串的子字符串,长度为 1 个字符(从 1 开始)
- CtoI(String):返回给定字符的十进制整数值(例如,'1' = 1,'2' = 2,...)
- ItoC(Integer):返回整数的十进制字符表示(例如,1 = '1'、2 = '2'、...)
- copies(count, string):返回 count 连接的字符串副本