我编写了递归方法来更改基础,但似乎无法使交互式解决方案起作用。我的递归方法如下所示:
public static String baseR(int y, int x){
if (y<x) {
return new String(""+y);
} else {
return new String (baseR(y/x,x)+("" +(y%x)));
}
}
我的迭代解决方案到目前为止看起来像这样:
public static String base(int y,int x){
int remainder = 0;
while(y!=0){
y=y/x;
remainder=y%x;
}
return new String(y+(""+ remainder));
}
他们没有打印出同样的东西,我尝试了一些不同的方法但没有成功,有没有人有任何指针?
答案 0 :(得分:1)
每次进入while
循环时,remainder
的值都会被覆盖。在覆盖之前,您应该“使用” remainder
的现有值。
另外,你应该在用商来覆盖y
的值之前计算余数的值。
public static String base(int y,int x){
int remainder = 0;
String value = "";
while(y!=0){
remainder=y%x;
value= remainder + value;
y=y/x;
}
return value;
}