Table of Contents
ToggleQuestion
Given an integer, n, print the following values for each integer i from 1 to n:
- Decimal
- Octal
- Hexadecimal (capitalized)
- Binary
Function Description
Complete the print_formatted function in the editor below.
print_formatted has the following parameters:
- int number: the maximum value to print
Prints
The four values must be printed on a single line in the order specified above for each i from 1 to number. Each value should be space-padded to match the width of the binary value of number.
Input Format
A single integer denoting n.
Constraints
1 <= n <= 99
Sample Input
17
Sample Output
1 1 1 1 2 2 2 10 3 3 3 11 4 4 4 100 5 5 5 101 6 6 6 110 7 7 7 111 8 10 8 1000 9 11 9 1001 10 12 A 1010 11 13 B 1011 12 14 C 1100 13 15 D 1101 14 16 E 1110 15 17 F 1111 16 20 10 10000 17 21 11 10001
Solution
def print_formatted(number):
width = len(bin(number)[2:]) # Determine the width based on the binary representation of 'number'
for i in range(1, number+1):
decimal = str(i)
octal = oct(i)[2:]
hexadecimal = hex(i)[2:].upper()
binary = bin(i)[2:]
# Print the formatted values
print(f"{decimal:>{width}} {octal:>{width}} {hexadecimal:>{width}} {binary:>{width}}")
# Test the function
n = int(input("Enter a number: "))
print_formatted(n)
This function takes an integer number
as input and calculates the width required for formatting by determining the length of the binary representation of number
. Then, it uses a loop to iterate from 1 to number
and calculates the decimal, octal, hexadecimal, and binary representations for each value of i
. Finally, it prints the formatted values using f-strings, ensuring each value is right-aligned with the specified width..
If you find anything wrong in this Solution, feel free to reach us in the comment section.