Python program to print decimal octal hex and binary of first n numbers


Suppose we have a value n. We have to print Decimal, Octal, Hexadecimal and Binary equivalent of first n numbers (1 to n) in four different columns. As we know, we can express the numbers with prefix characters d, o, X and b for decimal, octal, hexadecimal and decimal respectively.

So, if the input is like n = 10, then the output will be

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

To solve this, we will follow these steps −

  • l := (length of binary equivalent of n) - 2
  • for i in range 1 to n, do
    • f := blank string
    • for each character c in "doXb", do
      • if f is not empty, then
        • f := f concatenate one blank space
      • f := f + right aligned formatting string by converting l as string then concatenate c
    • pass i four times to the formatted string f and print the line

Example

Let us see the following implementation to get better understanding

def solve(n):
   l = len(bin(n)) - 2
   for i in range(1, n + 1):
      f = ""
      for c in "doXb":
         if f:
            f += " "
         f += "{:>" + str(l) + c + "}"
      print(f.format(i, i, i, i))

n = 10
solve(n)

Input

10

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

Updated on: 11-Oct-2021

789 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements