可能重复:
数字系统之间转换的有效算法
给定一个整数,编写一个将给定数字转换为数字(以 10 为基数)的程序。提示 - 给定的数字可以是任何基数,但基数未知。
可能重复:
数字系统之间转换的有效算法
给定一个整数,编写一个将给定数字转换为数字(以 10 为基数)的程序。提示 - 给定的数字可以是任何基数,但基数未知。
那是做不到的;在不知道来源基础的情况下,这个数字是模棱两可的。10
in basen
转换为n
in base 10
;有无限可能
我假设“未知”是指算法需要能够处理任何基础?否则这简直是不可能的。
所以你基本上是在要求函数 convert(number, base) = base10Number?
count = 0
total = 0
for each digit in number, from least significant to most significant
total = total + digit * base^count
count = count + 1
例如转换(355,8)
结果 = 237
您可以n
从 basec
到 base进行简单的算法更改b
,其中:
n
是组成数字的数字列表。c
是初始基数。b
是所需的基础。每个数字可能包含多个数字。下面是 Python 中 Wallar 算法的实现。
from math import *
def baseExpansion(n,c,b):
j = 0
base10 = sum([pow(c,len(n)-k-1)*n[k] for k in range(0,len(n))])
while floor(base10/pow(b,j)) != 0: j = j+1
return [floor(base10/pow(b,j-p)) % b for p in range(1,j+1)]
一旦你有了基础,这很容易做到。
您可以通过找到最高位来获得基数的下限。就像数字 175234 一样,底数必须至少为 8。但是您永远找不到上限:数字可以是从 8 到无穷大的任何底数。
相反,您可以打印出它的数字,假设第一个基数是 8、9 或 10。然后用户可以决定他/她的想法。
这是一个包含三种方法的小型 java 示例。
public class TestNumberBase {
public static void main(String[] args) {
System.out.println(converNumberTObase(100000, 2, 16));
}
public static int converNumberTObase(int inNum, int inBase, int outBase) {
return convertDecimalToOtherBase(convertDecimalEquivalent(inNum, inBase), outBase);
}
public static int convertDecimalEquivalent(int number, int inBase) {
int outNumber = 0;
int _base = inBase;
while (number > 0) {
int digit = number % 10;
number = number / 10;
outNumber = outNumber + (inBase / _base) * digit;
inBase = inBase*_base;
}
return outNumber;
}
public static int convertDecimalToOtherBase(int number, int outBase) {
int outNumber = 0;
int _base = 10, base =10;
while (number > 0) {
int digit = number % outBase;
number = number / outBase;
outNumber = outNumber + (base / _base) * digit;
base = base*_base;
}
return outNumber;
}
}
这是一个错误的问题,因为考虑到数字 7 它可能是八进制系统,十六进制系统。这是不可能决定的。我们必须知道输入数字的基数。我们可以这样写方法
公共 int convertToBase(int inNumber , int inBase , int outBase){
//哈哈哈哈哈哈
返回转换后的数字;}
问题陈述指出给定数字的基数是未知的。因此,要继续进行,必须假设该数字的基数。实际上可以安全地假设数字中具有最大值的数字表示可以在未知基数中计算的最大值。例如,如果将这个数字表示为 254,则可以假设数字系统由数字 0、1、2、3、4、5 或以 6 为基数组成。
if(!(((ascii >= '0') && (ascii <= '9')) || ((ascii >= 'A') && (ascii <= 'Z')))) {
printf("Illegal number, can have only digits (0-9) and letters (A-Z)");
希望这可以帮助。