To convert a decimal number to a hexadecimal number, use the following algorithm.
toHex(x)
- let S be the stack
- q = x / 16 and r = x % 16 // where q and r are the quotient and
remainder - S.push(q) if q > 0
- S.push(r)
- while (top element e > 15)
- pop out top element e
- q = e / 16
- r = e % 16
- S.push(q)
- S.push(r)
- let C is the char list
- while (stack is not empty)
- e = pop out top element
- if e is lie between 10 to 15 replace it with its corresponding hex digit
- C.append(e)
- return C.toString()
public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int decimal = scan.nextInt(); System.out.println(toHex(decimal)); } /** * Convert To Hex */ public static String toHex(final int X) { final Stack<Integer> S = new Stack<>(); int q = X / 16; int r = X % 16; S.push(r); if (q > 0) S.push(q); while (S.peek() > 15) { int e = S.pop(); q = e / 16; r = e % 16; S.push(r); S.push(q); } StringBuilder C = new StringBuilder(); while (!S.isEmpty()) { int e = S.pop(); switch (e) { case 10 -> C.append('A'); case 11 -> C.append('B'); case 12 -> C.append('C'); case 13 -> C.append('D'); case 14 -> C.append('E'); case 15 -> C.append('F'); default -> C.append(e); } } return C.toString(); } }