如何编写一个方法来返回任何基数的非递归数字的字符串表示



我编写了递归方法来更改基础,但似乎无法使交互解决方案发挥作用。我的递归方法如下:

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));
}

他们不会打印出相同的东西,我尝试了很多不同的方法都没有成功,有人有什么建议吗?

每次进入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;
}

最新更新