这段代码是我必须开发的项目的一部分.我需要编写一个java方法,将一个数字(基数为10)转换为另一个数字n.这是该类的代码:
public class converter {
public int from_10_to_n(int base, int newbase) {
int k = 0;
String res = "";
String output = "";
do { //Below I explain what I'm doing here
base /= newbase;
k = base % newbase;
res += String.valueOf(k);
} while (base != 0);
for(int i=res.length()-1; i>-1; i--) {
output += res.charAt(i);
}
return Integer.parseInt(output);
}
Run Code Online (Sandbox Code Playgroud)
我想以这种方式制作节目:

该do {} while();环路划分数和在K保存余.然后我创建一个for循环来反转字符串res(它有提醒).
顺便说一句,当我在我的主要方法中调用该方法时,我错过了最后一位数字.我的意思是:
converter k = new converter();
int e = k.from_10_to_n(a /*base 10 number*/, b /*Base n number*/);
System.out.println(a+" -> "+b+" is " + e);
Run Code Online (Sandbox Code Playgroud)
使用此代码,如果我想将231转换为基数4,我有321结果而不是3213.我检查了我的代码,但我找不到解决方案.任何的想法?
我和其他基地有同样的错误.例如31(基数10)是11111(基数2)但我的程序返回1111.
| 归档时间: |
|
| 查看次数: |
5981 次 |
| 最近记录: |