From 10fc0723f007b4e9ecbd26bafef598d5dfed921f Mon Sep 17 00:00:00 2001 From: fdzcxy212206320 <3186004297@qq.com> Date: Thu, 10 Oct 2024 16:57:33 +0800 Subject: [PATCH] ADD file via upload --- yuedongsheng.java | 87 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 yuedongsheng.java diff --git a/yuedongsheng.java b/yuedongsheng.java new file mode 100644 index 0000000..fdfc5d9 --- /dev/null +++ b/yuedongsheng.java @@ -0,0 +1,87 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +public class yuedongsheng { + + // 字符到数值的映射 + private static final Map charToValueMap = new HashMap<>(); + // 数值到字符的映射 + private static final Map valueToCharMap = new HashMap<>(); + + static { + // 初始化字符到数值的映射 + for (char c = '0'; c <= '9'; c++) { + charToValueMap.put(c, c - '0'); + } + for (char c = 'A'; c <= 'F'; c++) { + charToValueMap.put(c, c - 'A' + 10); + } + + // 初始化数值到字符的映射 + for (int i = 0; i <= 9; i++) { + valueToCharMap.put(i, (char) ('0' + i)); + } + for (int i = 10; i <= 15; i++) { + valueToCharMap.put(i, (char) ('A' + i - 10)); + } + } + + // 将任意进制的数转换为十进制 + public static int toDecimal(String number, int base) { + int decimalValue = 0; + int power = 0; + + for (int i = number.length() - 1; i >= 0; i--) { + char digit = number.charAt(i); + int value = charToValueMap.get(digit); + decimalValue += value * Math.pow(base, power); + power++; + } + + return decimalValue; + } + + // 将十进制数转换为任意进制 + public static String fromDecimal(int decimalValue, int base) { + if (decimalValue == 0) { + return "0"; + } + + StringBuilder result = new StringBuilder(); + while (decimalValue > 0) { + int remainder = decimalValue % base; + result.insert(0, valueToCharMap.get(remainder)); + decimalValue /= base; + } + + return result.toString(); + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // 输入原始进制和数 + System.out.print("请输入原始进制 (2-16): "); + int sourceBase = scanner.nextInt(); + System.out.print("请输入原始数: "); + String sourceNumber = scanner.next(); + + // 输入目标进制 + System.out.print("请输入目标进制 (2-16): "); + int targetBase = scanner.nextInt(); + + // 验证输入 + if (sourceBase < 2 || sourceBase > 16 || targetBase < 2 || targetBase > 16) { + System.out.println("进制必须在2到16之间!"); + return; + } + + // 转换 + int decimalValue = toDecimal(sourceNumber, sourceBase); + String targetNumber = fromDecimal(decimalValue, targetBase); + + // 输出结果 + System.out.println("转换后的数是: " + targetNumber); + } +} \ No newline at end of file