Skip to content
the poor coder

Hackerrank - String Formatting Solution

Poor Man
Published
Updated
Reading time
2 min read

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

  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  from  to . Each value should be space-padded to match the width of the binary value of .

Input Format

A single integer denoting .

Constraints

  • 1<=n<=99

Output Format

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

Sample Input

Text
17

Sample Output

Text
    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 in Python#

Python
def print_formatted(n):o
    binn = bin(n).replace("0b","")
    for i in range(1,n+1):
        deci = str(i)
        deci = (len(binn)-len(deci))*" "+deci
        
        octa = oct(i).replace("0o","")
        octa = (len(binn)-len(octa))*" "+octa
        
        hexi = hex(i).replace("0x","").upper()
        hexi = (len(binn)-len(hexi))*" "+hexi
        
        bina = bin(i).replace("0b","")
        bina = (len(binn)-len(bina))*" "+bina
        print(deci,octa,hexi,bina)


if __name__ == '__main__':
    n = int(input())
    print_formatted(n)

Keep going

2020

Hackerrank - Bus Station Solution

There are groups of friends, and each group is numbered from 1 to . The th group contains people. They live near a bus stop, and only a single bus operates on this route. An empty bus arrives at the bus stop and all the…

2020

Hackerrank - K Candy Store Solution

Jim enters a candy shop which has N different types of candies, each candy is of the same price. Jim has enough money to buy K candies. In how many different ways can he purchase K candies if there are infinite candies…

2020

Hackerrank - Diwali Lights Solution

On the eve of Diwali, Hari is decorating his house with a serial light bulb set. The serial light bulb set has N bulbs placed sequentially on a string which is programmed to change patterns every second. If at least one…

ESC