我必须创建一个递归方法将基数10转换为任何基数。 http://i.stack.imgur.com/nJMmm.jpg数字基数转换递归方法
- 如果base为2,然后用 “0b” 时前缀字符串
- 如果碱16然后前缀以 “0x”
- 如果base为10,则没有前缀(或后缀) 字符串在所有其他情况下
- postfix的用方括号
实例底部的字符串:
- 如果值是212和基为2,则该方法返回“0b11010100”
- 如果值是212和底座是10,则该方法返回“212”
- 如果值是212和底座是12,则该方法返回“119 [底座12]”
- 如果值是212和底座是20,则该方法返回“AC [基座20]”
- 如果值是212和底座是16,则该方法返回“0xD4”
- 如果值为212且基数为60,则方法返回“3.32 [基数为60]”
我的问题是与“在所有其他情况下后缀字符串与方括号中的基地”位。我想不明白。你能帮忙吗?
这里是我的通用解决方案:
public class NaturalNumber {
private int value;
public NaturalNumber(int value){
this.value = value;
}
public void setValue(int value){
this.value = value;
}
public int getValue(){
return value;
}
@Override
public String toString() {
return Integer.toString(value);
}
public String getValueBase(int base){
return getValueBase(value, base);
}
public static String getValueBase(int value, int base){
int quotient = value/base;
int remainder = value % base;
char ch = (char)(remainder+55);
if(quotient <= 0) {
if(remainder >= 10 && remainder <= 36){
if(base==16)
return "0x" + ch;
return "" + ch;
}
else {
if(base==2)
return "0b" + remainder;
if(base==16)
return "0x" + remainder;
return "" + remainder;
}
}
else
{
if(base > 36){
return getValueBase(quotient, base) + "." + remainder;
}
if(remainder >= 10 && remainder <= 36){
return getValueBase(quotient, base) + ch;
}
return getValueBase(quotient, base) + remainder;
}
}
public static void main(String[] args) {
NaturalNumber n = new NaturalNumber(68654332);
System.out.println(n.getValueBase(38));
}
}
您还没有提问。 – shmosel
我的问题是在最后加入[base]。你能帮忙吗? – Isidore
仍然没有问题。 – shmosel