这个 java 代码有什么问题?为什么不能用于"Any base to decimal conversion"?



我正在尝试将基数b的non转换为十进制no系统中的相应值。这段代码给出了错误的输出。

例如[1172]以8为基数的输出应该是[634]以10为基数的输出,但它给出的输出是100。

import java.util.*;     
public class Main{

public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int b = scn.nextInt();
int d = getValueIndecimal(n, b);
System.out.println(d);
}

public static int getValueIndecimal(int n, int b){
// write your code here
int k=0;
int result = 0;

while(n!=0)
{
int r = n % 10;
b = b^k;
result += r * b;
k = k+1;
n = n / 10;
}
return result;
}
}

^不是一个指数,它是一个异运算符。

对于指数,您可以使用Math.pow:

b = (int) Math.pow(b, k);

然而,请注意,您不会在迭代之间重置b,因此像这样使用pow也不正确。如果您想在迭代之间保持b,您只需要连续地将它乘以相同的基数:

public static int getValueIndecimal (int n, int b) {
int result = 0;
int pow = 1;

while(n != 0) {
int r = n % 10;
result += r * pow;
n /= 10;
pow *= b
}
return result;
}

相关内容

最新更新