Decimal to Octal and Hexadecimal
Problem
Read a non-negative integer and print it in octal (base 8) on the first line and in hexadecimal (base 16, with capital letters A to F) on the second line. Use the format shown in the example.
Constraints
- 0 <= n <= 2^31 - 1
Examples
Input
255
Output
Octal: 377 Hexadecimal: FF
Solutions
The same division method works for every base. We only change the divisor. A string of digit characters turns a remainder like 15 into the letter F.
/*
* Problem : Convert a decimal number to octal and hexadecimal.
* Input : One non-negative integer.
* Output : Two lines: Octal and Hexadecimal.
* Approach: Divide by the base and use a table of digit characters.
* Time : O(log n)
* Space : O(log n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method receives a number and a base (8 or 16). It returns the number written in that base.
static String convert(long number, int base) {
// Step 1: A table of all digit characters. The index in the table is the value of the digit.
String digits = "0123456789ABCDEF";
// Step 2: Zero is written as 0.
if (number == 0) {
return "0";
}
// Step 3: Collect the digits. We get them from the last digit to the first digit.
StringBuilder result = new StringBuilder();
while (number > 0) {
// Step 4: The remainder is the next digit. Look up the character in the table. Example: 255 % 16 = 15 -> 'F'.
result.append(digits.charAt((int) (number % base)));
// Step 5: Divide by the base to go to the next digit. Example: 255 / 16 = 15.
number = number / base;
}
// Step 6: Reverse the digits to get the correct order.
return result.reverse().toString();
}
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
System.out.println("Octal: " + convert(number, 8));
System.out.println("Hexadecimal: " + convert(number, 16));
}
}
Hints (2)
- Which base-10 values need letters in base 16?
- Use one method for both bases.