從鍵盤輸入一個不超過 8 位的正十六進制數字符串(大寫 A-F 表示 10-15),將其轉換為十進制數輸出。
輸入:FFFF 輸出:65535
package hex2dec;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next().trim().toUpperCase(); // 統一大寫
System.out.println(Long.parseLong(str, 16));
sc.close();
}
}
Long.parseLong(String s, int radix):radix 指定進制(2-36)result = result * radix + digitValueFFFFFFFF = 4,294,967,295 < Long.MAX_VALUE,long 足夠容納若輸入長度超過 16 位(超出 long 範圍),需使用 BigInteger:
import java.math.BigInteger;
import java.util.Scanner;
public class BigIntegerHex2Dec {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String hex = sc.next().trim();
// BigInteger 構造器:字符串 + 基數
BigInteger decimal = new BigInteger(hex, 16);
System.out.println(decimal); // 自動輸出十進制
sc.close();
}
}
public class ManualHex2Dec {
public static long hexToDec(String hex) {
hex = hex.toUpperCase();
long result = 0;
for (int i = 0; i < hex.length(); i++) {
char c = hex.charAt(i);
int digit;
if (c >= '0' && c <= '9') {
digit = c - '0';
} else if (c >= 'A' && c <= 'F') {
digit = c - 'A' + 10;
} else {
throw new IllegalArgumentException("Invalid hex character: " + c);
}
result = result * 16 + digit; // 霍納法則:result = result * base + digit
}
return result;
}
public static void main(String[] args) {
System.out.println(hexToDec("FFFF")); // 65535
System.out.println(hexToDec("1A3F")); // 6719
System.out.println(hexToDec("DEADBEEF")); // 3735928559
}
}
public class BaseConverter {
/** 任意進制 (2-36) 字符串轉十進制 long */
public static long toDecimal(String number, int base) {
if (base < 2 || base > 36) throw new IllegalArgumentException("Base must be 2-36");
number = number.toUpperCase();
long result = 0;
for (char c : number.toCharArray()) {
int digit = Character.digit(c, base); // JDK 內置字符轉數值
if (digit == -1) throw new IllegalArgumentException("Invalid digit: " + c);
result = result * base + digit;
}
return result;
}
/** 十進制 long 轉任意進制 (2-36) 字符串 */
public static String fromDecimal(long number, int base) {
if (base < 2 || base > 36) throw new IllegalArgumentException("Base must be 2-36");
if (number == 0) return "0";
StringBuilder sb = new StringBuilder();
boolean negative = number < 0;
long n = negative ? -number : number;
while (n > 0) {
int digit = (int)(n % base);
sb.append(Character.forDigit(digit, base)); // 數值轉字符
n /= base;
}
if (negative) sb.append('-');
return sb.reverse().toString();
}
}
| 陷阱 | 說明 | 解決方案 |
|---|---|---|
| 輸入包含小寫 | parseLong 不區分大小寫,但手寫算法需統一 | .toUpperCase() 或 Character.digit() 自動處理 |
| 前綴 0x/0X | parseLong 不支援前綴 | 手動移除:str.replaceFirst("^0[xX]", "") |
| 超長溢出 | 8 位內安全,超長需 BigInteger | new BigInteger(str, 16) |
| 負數處理 | 題目限定正數,通用場景需處理符號位 | BigInteger 支援負號,手寫需單獨判斷 |
Long.parseLong(str, 8)Long.parseLong(str, 2)Long.toHexString(n) / Integer.toHexString(n)BigInteger 構造器 + toString(radix)進制轉換是計算機科學基礎中的基礎,既是 OJ 入門必刷,也是理解位運算、編碼解碼、哈希算法、加密協議的前置知識。建議熟練掌握 JDK 內置 API、BigInteger 大數處理、手寫霍納法則三種層面的實現能力。