[英]Convert Decimal to Hex using Recursive method Java, without using Strings, java.utils and switch
附加条件:
1)不要使用字符串处理数字中的数字。
2)不要使用 jdk utils 和 if/switch 来映射 AF 字母。
这是最后一项任务:
编写一个递归函数,用于从 N 元中的十进制系统中传输自然数。 主程序中的值 N 是从键盘输入的 (16 >= N >= 2)。
导入 java.util.Scanner;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Insert number ");
int number = s.nextInt();
System.out.println("Insert Base");
int n = s.nextInt();
System.out.println(convertFromDecimalToBaseN(number, n, 1));
}
public static Integer convertFromDecimalToBaseN(int num, int n, int pow) { //pow always = 1;
Integer r = num % n;
if (num < n)
return new Double((Math.pow(10, pow - 1)) * r.doubleValue()).intValue();
return convertFromDecimalToBaseN(num / n, n, pow + 1) +
new Double(Math.pow(10, pow - 1) * r.doubleValue()).intValue();
}
}
像这样对AF字母使用表格查找
private static char charMap[] = {'0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Insert number ");
int number = s.nextInt();
System.out.println("Insert Base");
int n = s.nextInt();
System.out.println(convertFromDecimalToBaseN(number, n, ""));
}
public static String convertFromDecimalToBaseN(int num, int n, String result) {
int r = num % n;
int rest = num / n;
if (rest > 0) {
return convertFromDecimalToBaseN(rest, n, charMap[r] + result);
}
return charMap[r] + result;
}
这里的代码使用java中的递归方法将十进制转换为十六进制。
import java.util.Scanner;
public class DecimalToHexaDemo
{
char hexa[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int temp;
String hexaDecimal = "";
String hexadecimal(int num) // using recursive method
{
if(num != 0)
{
temp = num % 16;
hexaDecimal = hexa[temp] + hexaDecimal;
num = num / 16;
hexadecimal(num);
}
return hexaDecimal;
}
public static void main(String[] args)
{
DecimalToHexaDemo dth = new DecimalToHexaDemo();
int decimalNumber;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter decimal number: ");
decimalNumber = sc.nextInt();
System.out.println("The hexadecimal value is : ");
String str = dth.hexadecimal(decimalNumber);
System.out.print(str);
sc.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.