尝试在Java中不使用方法或数组将整数转换为十六进制
这是我到目前为止得到的,但它向后打印出十六进制。如何将其切换为正向,或者有没有比我现在更容易的方法将整数转换为十六进制。这是一个家庭作业,我不允许使用数组或预定义的方法(即toHexString()) 你可以用 这里的想法是最后打印最大的数字。为此,您反复调用相同的函数,每次将数字减少一位数。每次输入函数时,都要检查结束条件是否满足(没有更多的数字)。这就是所谓的。一旦满足此条件,您将返回方法调用链,每次打印下一个最高数字 例如,输入尝试在Java中不使用方法或数组将整数转换为十六进制,java,Java,这是我到目前为止得到的,但它向后打印出十六进制。如何将其切换为正向,或者有没有比我现在更容易的方法将整数转换为十六进制。这是一个家庭作业,我不允许使用数组或预定义的方法(即toHexString()) 你可以用 这里的想法是最后打印最大的数字。为此,您反复调用相同的函数,每次将数字减少一位数。每次输入函数时,都要检查结束条件是否满足(没有更多的数字)。这就是所谓的。一旦满足此条件,您将返回方法调用链,每次打印下一个最高数字 例如,输入1337的流程如下: depth 0: divided = 1
1337
的流程如下:
depth 0: divided = 1337 / 16 = 83, remainder = 9
depth 1: divided = 83 / 16 = 5, remainder = 3
depth 2: divided = 5 / 16 = 0, remainder = 5
depth 3: end condition met
print remainder = 5
print remainder = 3
print remainder = 9
它打印
539
如果您想走非递归路线,请在进入循环并在其上构建之前声明一个字符串,而不是打印到系统。每次循环迭代时输出:
String output = "";
while (num > 0) {
remainder = num % 16;
if (remainder == 10) {
output = "a" + output;
} else if (remainder == 11) {
output = "b" + output;
} else if (remainder == 12) {
output = "c" + output;
} else if (remainder == 13) {
output = "d" + output;
} else if (remainder == 14) {
output = "e" + output;
} else if (remainder == 15) {
output = "f" + output;
} else {
output = remainder + output;
}
num = num / 16;
}
System.out.println(output);
迭代解(仅适用于正整数):
在循环的每次迭代中,您是否考虑过在循环过程中存储输出,并在循环结束时进行一次打印,而不是打印到System.out
?这将允许您在最后一分钟对正在打印的内容进行操作。需要考虑的问题。我确实考虑过这一点,但考虑到我不能使用数组,而且答案中会有1-8个字符。我将添加一个解决方案来扩展我提出的观点。已经发布的递归解决方案似乎也是一个很好的解决方案。太好了!非常感谢。我不知道你可以这样处理字符串,只添加字母。为了更有效,你需要使用StringBuilder对象并附加到该对象,然后在末尾执行sb.toString()。字符串是不可变的,所以您将为每个循环创建一个新字符串。这是真的。我只是想维持他的作业规则,不使用预定义的方法,所以我假设StringBuilder.append()
是不可能的。如果该规则仅适用于十六进制转换本身,那么无论如何,我都会考虑使用StringBuilder
。这就是我直接使用递归解决方案的原因。使用串联或StringBuilder
构建字符串似乎与使用容器的方法非常相似——尽管我认为这个问题没有足够的约束条件可以肯定地说:)
depth 0: divided = 1337 / 16 = 83, remainder = 9
depth 1: divided = 83 / 16 = 5, remainder = 3
depth 2: divided = 5 / 16 = 0, remainder = 5
depth 3: end condition met
print remainder = 5
print remainder = 3
print remainder = 9
String output = "";
while (num > 0) {
remainder = num % 16;
if (remainder == 10) {
output = "a" + output;
} else if (remainder == 11) {
output = "b" + output;
} else if (remainder == 12) {
output = "c" + output;
} else if (remainder == 13) {
output = "d" + output;
} else if (remainder == 14) {
output = "e" + output;
} else if (remainder == 15) {
output = "f" + output;
} else {
output = remainder + output;
}
num = num / 16;
}
System.out.println(output);
public static String toHex(int value) {
if (value == 0)
return "0";
StringBuffer result = new StringBuffer();
while (value > 0) {
int x = value & 0b1111;
char hex = (char) (x < 10 ? '0' + x : 'A' + x - 10);
result.insert(0, hex);
value >>= 4;
}
return result.toString();
}
@Test
public void testHex() {
Random random = ThreadLocalRandom.current();
for (int i = 0; i < 1000000; i++) {
int value = random.nextInt();
if (value >= 0) {
Assert.assertEquals(Integer.toHexString(value).toUpperCase(), toHex(value));
}
}
}