问题
假设我有一个字符串或数组,它表示基N,N>1中的一个数字,其中N是2的幂。假设所表示的数字大于系统作为实际数字( int或double等)所能处理的数字。
如何将其转换为十进制字符串?
对于满足上述条件(二进制,十六进制,.)的任意一个基N,我都是开放的。也就是说,如果你有一个对至少一个碱基N有效的解决方案,我感兴趣:)
示例:
Input: "10101010110101"
-
Output: "10933"
发布于 2010-03-07 23:25:58
这取决于特定的语言。有些是对任意长度整数的本机支持,另一些则可以使用GMP之类的库。在此之后,只需在表中查找数字值,然后适当地乘以即可。
发布于 2010-03-07 23:37:26
这是我上学期修的一门基于Python的计算机科学课程,它的目的是处理16级以下的问题。
import string
def baseNTodecimal():
# get the number as a string
number = raw_input("Please type a number: ")
# convert it to all uppercase to match hexDigits (below)
number = string.upper(number)
# get the base as an integer
base = input("Please give me the base: ")
# the number of values that we have to change to base10
digits = len(number)
base10 = 0
# first position of any baseN number is 1's
position = 1
# set up a string so that the position of
# each character matches the decimal
# value of that character
hexDigits = "0123456789ABCDEF"
# for each 'digit' in the string
for i in range(1, digits+1):
# find where it occurs in the string hexDigits
digit = string.find(hexDigits, number[-i])
# multiply the value by the base position
# and add it to the base10 total
base10 = base10 + (position * digit)
print number[-i], "is in the " + str(position) + "'s position"
# increase the position by the base (e.g., 8's position * 2 = 16's position)
position = position * base
print "And in base10 it is", base10
基本上,它以输入作为字符串,然后遍历并将每个“数字”乘以基数-10的位置。实际上,每个数字都会在字符串hexDigits
中检查其索引位置,该字符串用作数值。
假设它返回的数字实际上比编程语言所支持的要大,那么您可以构建一个代表整个数字的Ints数组:
[214748364, 8]
表示2147483648 (一个Java int
无法处理的数字)。
发布于 2010-03-08 00:55:09
这是我刚刚编写的一些php代码:
function to_base10($input, $base)
{
$result = 0;
$length = strlen($input);
for ($x=$length-1; $x>=0; $x--)
$result += (int)$input[$x] * pow($base, ($length-1)-$x);
return $result;
}
它非常简单:只是一个循环遍历输入字符串的每一个字符
这适用于任何小于10的碱基,但它可以很容易地扩展到支持较高的碱基(A->11,B->12等)。
编辑:哦,没有看到python代码:)是的,这更酷
https://stackoverflow.com/questions/2398427
复制相似问题