
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- if f is not empty, then
- 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
- Related Articles
- How to Convert Decimal Number to Binary/Octal/Hex Number or Vice Versa in Excel?
- C++ Program to convert Decimal Numbers to Octal
- How to Convert Decimal to Binary, Octal, and Hexadecimal using Python?
- Python program to convert hex string to decimal
- Python program to convert float decimal to octal number
- How to Convert Hex Numbers to Decimal Numbers in Excel?
- C# Program to Convert Decimal to Binary\n
- How to Convert Octal to Binary?\n
- Java Program to convert Decimal to Octal
- Golang Program to convert Decimal to Octal
- Swift Program to convert Decimal to Octal
- Program to generate first n lexicographic numbers in python
- Program to find sum of first N odd numbers in Python
- C# program to convert decimal to Octal number
- Java Program to Display Numbers and Sum of First N Natural Numbers

Advertisements