因此,这是我到目前为止的内容,但它向后打印出十六进制。我如何将其切换为正向,或者有比我做的更简单的方法来将整数转换为HexDecimal。这是一项家庭作业,我不允许使用数组或预定义方法(IE .toHexString())。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int num = scn.nextInt();
int remainder;
while (num > 0) {
remainder = num % 16;
if (remainder == 10) {
System.out.print("a");
} else if (remainder == 11) {
System.out.print("b");
} else if (remainder == 12) {
System.out.print("c");
} else if (remainder == 13) {
System.out.print("d");
} else if (remainder == 14) {
System.out.print("e");
} else if (remainder == 15) {
System.out.print("f");
} else {
System.out.print(remainder);
}
num = num / 16;
}
}
}
如果要走非递归路线,String
请在进入循环并建立循环之前声明a ,而不是打印System.out
每次循环迭代:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句