Complete the method toBase12() below that converts the given positive integer, n, into the duodecimal base (base-12)
Question:
Complete the method toBase12() below that converts the given positive integer, n, into the duodecimal base (base-12) and returns the duodecimal String. Duodecimal numbers have place values that are powers of 12 (1's place, 12's place, 144's place, 1728's place, and so on). Each place can have digits equivalent to the decimal values 0 to 11. To represent 10 and 11, use the letters A and B, respectively.
For example, the value 20A in duodecimal is:
2 x 12 2 + 0 x 12 1 + 1 x 12 0 = 2 x 144 + 0 x 12 + 1 x 1 = 288 + 0 + 1 = 289
To convert the given base-10 number to duodecimal, use a process of repeated division to find quotients and remainders. The quotients are used in the next step. The remainders are the digits of the result in duodecimal, in reverse order. For example, to convert the decimal number 4259 to base-12:
4259 / 12 = 354 and 4259 % 12 = 11 = "B" in duo decimal
354 / 12 = 29 and 354 % 12 = 6
29 / 12 = 2 and 29 % 12 = 5
2/ 12 = 0 and 2 % 12 = 2
so, reading the remainders in reverse order we get that 4259 in base-10 is 256B in base-12 (duodecimal).
To write the method recursively:
consider the base case of returning just the number itself when it is less than 12 (the quotient will be 0 when dividing by 12 and the remainder is the number). return "A" or "B" if the number is 10 or 11.
condider the recursive case of the number greater than or equal to 12. In this case, first call the method recursively using the quotient and concatenate the result (use the + operator to connect the Strings) with the result of another recursive call using the remainder. Return the concatenated result of the two recursive calls.
Starter Code:-
public class Duodecimal {
public static String toBase12(int n) {
//TODO: complete this method
}
}
Discrete Mathematics and Its Applications
ISBN: 978-0073383095
7th edition
Authors: Kenneth H. Rosen