使用一个栈,将十进制转换成二进制,八进制或十六进制

用Java语言编写,加适当解释,谢谢!

第1个回答  推荐于2017-10-03
public class Change {
public static void main(String[] args) {
System.out.println(binary(100));
System.out.println(octonary(100));
System.out.println(hexadecimal(1000));
}

public static String binary(int a){
byte[] b = new byte[1024];
String s="";
int i=0;
while(a>0){
int temp = a%2;
b[i] = (byte)temp;
i++;
a = a/2;
}
while(--i>=0){
s+=b[i];
}
return s;
}

public static String octonary(int a){
String s = "";
byte [] b = new byte[1024];
int i =0;
while(a>0){
int temp = a%8;
b[i] =(byte)temp;
i++;
a /=8;
}
while(--i>=0){
s += b[i];
}
return s;
}

public static String hexadecimal(int a){
String s ="";
byte [] b = new byte[1024];
int i=0;
while(a>0){
int temp = a%16;
b[i] = (byte)temp;
i++;
a /= 16;
}
String [] str = {"A","B","C","D","E","F"};
while(--i>=0){
s +=b[i]>10?str[b[i]-10]:b[i];
}
return s;
}
}
当然Java本身就有转换函数
十进制转成十六进制:
Integer.toHexString(int i)
十进制转成八进制
Integer.toOctalString(int i)
十进制转成二进制
Integer.toBinaryString(int i)
你也可以直接使用这些,不用自己写方法本回答被提问者和网友采纳
相似回答