|
|
|
@ -1,24 +1,20 @@
|
|
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
|
|
public class BaseConversion {
|
|
|
|
|
// 将任意R进制数转换为十进制数
|
|
|
|
|
public static int convertToDecimal(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 digitValue;
|
|
|
|
|
|
|
|
|
|
// 处理数字和字母(十六进制)
|
|
|
|
|
if (Character.isDigit(digit)) {
|
|
|
|
|
digitValue = digit - '0'; // 0-9
|
|
|
|
|
digitValue = digit - '0';
|
|
|
|
|
} else {
|
|
|
|
|
digitValue = Character.toUpperCase(digit) - 'A' + 10; // A-F
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 累加到十进制值
|
|
|
|
|
decimalValue += digitValue * Math.pow(base, power);
|
|
|
|
|
power++;
|
|
|
|
|
}
|
|
|
|
@ -26,11 +22,9 @@ public class BaseConversion {
|
|
|
|
|
return decimalValue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 将十进制数转换为任意R进制数
|
|
|
|
|
public static String convertFromDecimal(int number, int base) {
|
|
|
|
|
StringBuilder result = new StringBuilder();
|
|
|
|
|
|
|
|
|
|
// 特殊情况:如果number为0,直接返回0
|
|
|
|
|
if (number == 0) {
|
|
|
|
|
return "0";
|
|
|
|
|
}
|
|
|
|
@ -38,37 +32,34 @@ public class BaseConversion {
|
|
|
|
|
while (number > 0) {
|
|
|
|
|
int remainder = number % base;
|
|
|
|
|
if (remainder < 10) {
|
|
|
|
|
result.append((char) ('0' + remainder)); // 0-9
|
|
|
|
|
result.append((char) ('0' + remainder));
|
|
|
|
|
} else {
|
|
|
|
|
result.append((char) ('A' + remainder - 10)); // A-F
|
|
|
|
|
result.append((char) ('A' + remainder - 10));
|
|
|
|
|
}
|
|
|
|
|
number /= base;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 反转结果字符串
|
|
|
|
|
return result.reverse().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("请输入目标进制 (2-16): ");
|
|
|
|
|
int targetBase = scanner.nextInt();
|
|
|
|
|
scanner.nextLine(); // 消耗换行符
|
|
|
|
|
scanner.nextLine();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 输入要转换的数字
|
|
|
|
|
System.out.print("请输入要转换的数字: ");
|
|
|
|
|
String number = scanner.nextLine();
|
|
|
|
|
|
|
|
|
|
// 进行进制转换
|
|
|
|
|
|
|
|
|
|
int decimalValue = convertToDecimal(number, sourceBase);
|
|
|
|
|
String result = convertFromDecimal(decimalValue, targetBase);
|
|
|
|
|
|
|
|
|
|
// 输出结果
|
|
|
|
|
|
|
|
|
|
System.out.println("转换结果: " + result);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|