String Formatting in Python - HackerRank Solution

Problem Statement :

Given an integer, n, print the following values for each integer i from 1 to n:

     1. Decimal

     2. Octal

     3. Hexadecimal (capitalized)

     4. Binary

The four values must be printed on a single line in the order specified above for each i from 1 to n. Each value should be space-padded to match the width of the binary value of n.


Input Format:

A single integer denoting n.


Constraints:

 1<=n<=99


Output Format:

Print n lines where each line i (in the range 1<=i<=n) contains the respective decimal, octal, capitalized hexadecimal, and binary values of i. Each printed value must be formatted to the width of the binary value of n.


Solution:

import math

n = int(input())

max_length = math.floor(math.log(n, 2)) + 1

for i in range(1, n+1):
    d = str(i).rjust(max_length)
    o = str(oct(i))[2:].rjust(max_length)
    h = str(hex(i))[2:].upper().rjust(max_length)
    b = bin(i)[2:].lstrip('0').rjust(max_length)
    print('{} {} {} {}'.format(d,o,h,b))



Disclaimer:- 

The above hole problem statement is given by hackerrank.com but the solution is generated by the Hackerranksolution.site authority if any of the queries regarding this post or website fill the following contact form thank you.
Next Post Previous Post
No Comment
Add Comment
comment url