牛客網測試題 把十六進位制數字轉換為十進位制數字

coderlwz發表於2024-09-07
 1 /**
 2  * 把十六進位制數字轉換為十進位制數字
 3  * @param hexSrcStr
 4  * @return
 5  * 170
 6  */
 7 public static String convertHex2Decimal(String hexSrcStr){
 8     if (hexSrcStr==null || hexSrcStr.trim().length()==0){
 9         return null;
10     }
11     if (!hexSrcStr.startsWith("0x")){
12         System.out.println("十六進位制數字輸入非法!");
13         return null;
14     }
15     String substring1 = hexSrcStr.substring(2);
16     for (int i = 0; i < substring1.length(); i++) {
17         char charAt = substring1.charAt(i);
18         if (!(Character.isDigit(charAt) || (Character.isUpperCase(charAt) && charAt >= 'A' && charAt <= 'F'))){
19             return null;
20         }
21     }
22 
23     HashMap<Character, Integer> characterIntegerHashMap = new HashMap<>();
24     characterIntegerHashMap.put('A',10);
25     characterIntegerHashMap.put('B',11);
26     characterIntegerHashMap.put('C',12);
27     characterIntegerHashMap.put('D',13);
28     characterIntegerHashMap.put('E',14);
29     characterIntegerHashMap.put('F',15);
30 
31     // 0xAA
32     String substring = hexSrcStr.substring(2);
33     int length = substring.length();
34     int sum=0;
35     int ret=1;
36     for (int i = length-1; i >=0 ; i--) {
37         if (i==0){
38             ret=1;
39         }else {
40             for (int j =0;j<i;j++) {
41                 ret*=16;
42             }
43         }
44 
45         char charAt = substring.charAt((length-1)-i);
46         Integer integer=0;
47         Integer integer1=0;
48         if (Character.isDigit(charAt)){
49             String charStr = String.valueOf(charAt);
50             integer = Integer.valueOf(charStr);
51             integer*=ret;
52         }else if (Character.isUpperCase(charAt)){
53             integer1 = characterIntegerHashMap.get(charAt);
54             integer1*=ret;
55         }
56 
57         if (Character.isDigit(charAt)){
58             sum+=integer;
59             ret=1;
60         }else if (Character.isUpperCase(charAt)){
61             sum+=integer1;
62             ret=1;
63         }
64     }
65 
66     return String.valueOf(sum);
67 }

相關文章