java十进制到(二进制,八进制,十六进制)的转换的优化

 1 import java.util.Scanner;
 2 
 3 public class ArrayTest {
 4 
 5     public static void main(String[] args) {
 6         int n, m;
 7         Scanner cin = new Scanner(System.in);
 8         n = cin.nextInt();
 9         m = cin.nextInt();
10         toBin(n);
11         toHex(m);
12     }
13 
14     public static void toBin(int n) {// 十进制--->二进制
15         tran(n, 1, 1);
16     }
17 
18     public static void toHex(int n) {// 十进制--->十六进制
19         tran(n, 15, 4);
20     }
21 
22     public static void toBa(int n) {// 十进制--->八进制
23         tran(n, 7, 3);
24     }
25 
26     public static void tran(int n, int base, int offest) {
27         if (n == 0) {
28             System.out.println(0);
29             return;
30         }
31         char[] ch = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
32                 'B', 'C', 'D', 'E', 'F' };
33         char[] str = new char[100];
34         int pos = str.length;
35         while (n != 0) {
36             int temp = n & base;
37             str[--pos] = ch[temp];
38             n = n >>> offest;
39 
40         }
41         for (int i = pos; i < str.length; i++) {
42             System.out.println(str[i]);
43         }
44     }
45 
46 }
View Code

 

posted @ 2013-12-05 19:16  天天AC  阅读(319)  评论(0编辑  收藏  举报