我必須創建一個遞歸方法將基數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