题目:实现将10进制数字字符串转换为16进制数字字符串,如155转换为0x9B,要求不得使用任何第三方提供字符串与数字转换方法,如C语言的atoi,java的Integer.ParseInt等等
方法1:
public class Test {
public static void main(String[] args) {
// 测试数据
int a = 155;
// 进行转换
String b = tenChangeHex(a);
// 获取结果
String result = "0x" + b;
// 输出结果
System.out.println(result);
}
// 将10进制整数正整数变成16进制
private static String tenChangeHex(int a) {
StringBuilder sb = new StringBuilder();
change(sb, a);
return sb.toString();
}
// 将10进制整数正整数变成16进制
private static void change(StringBuilder sb, int a) {
if (a == 0) {
return;
}
sb.insert(0, toHexChar(a % 16));
change(sb, a / 16);
}
//将0~15的十进制数转换成0~F的十六进制数
private static char toHexChar(int hexValue) {
if (hexValue >= 0 && hexValue <= 9) {
return (char) (hexValue + '0');
} else {
return (char) (hexValue - 10 + 'A');
}
}
}
结果:
0x9B
解释:
使用的递归和除基倒取余的思想
方法2:
public class Test {
public static void main(String[] args) {
// 测试数据
int a = 155;
// 进行转换
String b = tenChangeHex(a);
// 获取结果
String result = "0x" + b;
// 输出结果
System.out.println(result);
}
public static String tenChangeHex(int a) {
StringBuilder str = new StringBuilder();
while (a != 0) {
str.insert(0, toHexChar(a % 16));
a /= 16;
}
return str.toString();
}
//将0~15的十进制数转换成0~F的十六进制数
private static char toHexChar(int hexValue) {
if (hexValue >= 0 && hexValue <= 9) {
return (char) (hexValue + '0');
} else {
return (char) (hexValue - 10 + 'A');
}
}
}
结果:
0x9B
解释:
使用的while循环和除基倒取余的思想