HackerRank Python: String Formatting Solution

Table of Contents

Question

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.

Sharing Is Caring:

Leave a Comment