Friday, July 5, 2024
HomeLanguagesPythonPython program to Represent Negative Integers in binary format

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.

Python3




# 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.

Python3




# 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. 

Python3




# 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

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments