Loading...
Loading...
A computer science lab shows numbers in binary, octal and hexadecimal. Given a decimal number n and a base b, print n written in base b. Digits above 9 are the capital letters A to F (10 is A, 15 is F).
Do it without Strings: write a recursive method static void printInBase(long n, int b) that prints the digits from the most significant one, and a helper static char digitChar(int d) that turns a value 0-15 into its character.
Example 1
Input
10 2
Output
1010
10 = 8 + 2, so 1010 in binary.
Example 2
Input
255 16
Output
FF
255 = 15 × 16 + 15, so FF.
Try the problem first. Open one hint at a time.
The last digit in base b is n % b, and the other digits are the digits of n / b.
Print the other digits first with a recursive call, then print the last digit: this puts them in the right order.
Stop when n < b: it is a single digit. This also makes 0 print as 0.
Characters are numbers too: (char) ('0' + d) for 0-9 and (char) ('A' + d - 10) for 10-15.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor