Write Python code for converting a decimal number to it’s binary equivalent and vice-versa.
Example:
From decimal to binary
Input : 8
Output : 1 0 0 0
From binary to decimal
Input : 100
Output : 4
Decimal to binary
Keep calling conversion function with n/2 till n > 1,
later perform n % 1 to get MSB of converted binary number.
Example :- 7
1). 7/2 = Quotient = 3(greater than 1), Remainder = 1.
2). 3/2 = Quotient = 1(not greater than 1), Remainder = 1.
3). 1%2 = Remainder = 1.
Therefore, answer is 111.
Python3
def decimalToBinary(n):
if (n > 1 ):
decimalToBinary(n / / 2 )
print (n % 2 , end = ' ' )
if __name__ = = '__main__' :
decimalToBinary( 8 )
print ( "\n" )
decimalToBinary( 18 )
print ( "\n" )
decimalToBinary( 7 )
print ( "\n" )
|
Output
1 0 0 0
1 0 0 1 0
1 1 1
Time Complexity: O(log n)
Auxiliary Space: O(1)
Decimal to binary using bin():
Python3
def decimalToBinary(n):
return bin (n).replace( "0b" ,"")
if __name__ = = '__main__' :
print (decimalToBinary( 8 ))
print (decimalToBinary( 18 ))
print (decimalToBinary( 7 ))
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Binary to decimal
Example -: 1011
1). Take modulo of given binary number with 10.
(1011 % 10 = 1)
2). Multiply rem with 2 raised to the power
it's position from right end.
(1 * 2^0)
Note that we start counting position with 0.
3). Add result with previously generated result.
decimal = decimal + (1 * 2^0)
4). Update binary number by dividing it by 10.
(1011 / 10 = 101)
5). Keep repeating upper steps till binary > 0.
Final Conversion -: (1 * 2^3) + (0 * 2^2) +
(1 * 2^1) + (1 * 2^0) = 11
Python3
def binaryToDecimal(binary):
decimal, i = 0 , 0
while (binary ! = 0 ):
dec = binary % 10
decimal = decimal + dec * pow ( 2 , i)
binary = binary / / 10
i + = 1
print (decimal)
if __name__ = = '__main__' :
binaryToDecimal( 100 )
binaryToDecimal( 101 )
binaryToDecimal( 1001 )
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Binary to decimal using int():
Python3
def binaryToDecimal(n):
return int (n, 2 )
if __name__ = = '__main__' :
print (binaryToDecimal( '100' ))
print (binaryToDecimal( '101' ))
print (binaryToDecimal( '1001' ))
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Method: Using format specifier
Python3
n = 4
print ( '{0:b}' . format (n))
|
Built-in format function:
Another approach for converting decimal to binary is to use the built-in format function. This approach involves formatting a decimal number as a binary string using the b format specifier. To convert a binary string back to its decimal equivalent, you can use the built-in int function with the base parameter set to 2. For example:
Python3
n = 4
binary = format (n, 'b' )
print (binary)
binary = '100'
decimal = int (binary, 2 )
print (decimal)
|
Time complexity: O(1), or constant time. The code performs a fixed number of operations regardless of the size of the input. Specifically, the code:
- Reads an integer from the user and assigns it to n.
- Converts n to a string in binary format and assigns the result to binary.
- Converts binary to an integer and assigns the result to decimal.
- Prints binary and decimal.
The time complexity of the code is determined by the time it takes to read an integer from the user, which is a fixed operation. Therefore, the time complexity of the code is O(1).
Auxiliary Space: O(1), or constant space. The code uses a fixed number of variables, regardless of the size of the input. Specifically, the code uses:
- The variable n to store a single integer.
- The variable binary to store a string representation of n in binary format.
- The variable decimal to store the decimal equivalent of binary.
Since the number of variables used is fixed and does not depend on the size of the input, the auxiliary Space of the code is O(1).
It’s worth noting that the specific time and space complexity of the conversion operations in this code may depend on the implementation of the built-in format and int functions. However, in general, these operations take O(1) time and space.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!