This is an extension to a previous question of mine, but I'm required to do this problem without this function. I have to use recursion only. Any thoughts?
An example; 20A would be:
2 x 12^2 + 0 x 12^1 + 10 x 12^0 = 2 x 144 + 0 x 12 + 10 x 1 = 288 + 0 + 10 = 298
public class Duodecimal {
public static String toBase12(int n) {
if (n < 10)
return Integer.toString(n);
if (n == 10)
return "A";
if (n == 11)
return "B";
return toBase12(n / 12) + toBase12(n % 12);
}
}
Well, you've figured it out for n == 10. Surely you can use the same technique for n == 9. If you want an alternate idea, imagine you have the string '0123456789AB'. String has a method to ask for the character at a given index. NOw, what digit is at position '9' in that string? What is at 10? Exactly. This method is charAt
.
I bet you can finish this homework with this hint:)
With a little thought, you could extend this to convert any base from 2 thru 16.
base
or radix
digits
as "0123456789ABCDEF"
radix
is within an allowable range.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.