Open In App

Python program to Represent Negative Integers in binary format

Given a Negative Integer, the task is to write a Python program to convert the integer into binary format. 

Examples:



Input: -14
Output: -1110

Input: -12
Output: -1100

Input: -32
Output: -100000

Let’s implement this for the number in different ways :

Method 1: Using format specifier ‘b’

In format specifier type b is used to convert the integer into binary form.






# Input number
x = -14
 
# Using b format specifier
print("{:b}".format(x))

Output : 

-1110

Time Complexity : O(1)

Space Complexity : O(1)

Method 2: Using bin() function

Python bin() function returns the binary string of a given integer.




# Using bin function
# Replacing "0b" i.e. bydefault
# including in result
print(int(bin(-12).replace("0b", "")))

Output : 

-1100

Time Complexity : O(log n)

Space Complexity : O(m)

Method 3: Using f-strings 

F-strings helps to embed python expressions inside string literals for formatting. 




# Using f-string
print(f"{-32:b}")

Output : 

-100000

Time Complexity : O(1)

Space Complexity : O(1)

Note: For more information about Representation of Negative Binary Numbers please read this article – Click


Article Tags :