Loading...
Loading...
An electronics lab converts numbers between bases 2 and 16 (binary, octal, decimal, hex and the rest).
Write a utility class BaseConverter with static final String DIGITS = "0123456789ABCDEF", a static method long toDecimal(String value, int base) that returns -1 when a digit is not allowed in that base, and a static method String fromDecimal(long n, int base). Do not use Integer.parseInt(s, radix) or Long.toString(n, radix).
INVALID when the value has a digit its base does not allow.Example
Input
4 255 10 16 ff 16 2 777 8 10 19 8 10
Output
FF 11111111 511 INVALID
9 is not an octal digit, so the last value is invalid.
Try the problem first. Open one hint at a time.
DIGITS.indexOf(ch) turns a character into its value; -1 or a value ≥ base means invalid.
To read a value: start at 0 and for each digit do n = n * base + digit.
To write a value: take n % base as the last digit, then n /= base, and build the text from the right.
Handle 0 on its own: the division loop would produce an empty String.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor