Last active
August 9, 2022 11:21
-
-
Save Nishith-Savla/830f604f1eb12cd67fe94b33a9b13d2d to your computer and use it in GitHub Desktop.
Program to find the 1's complement of a binary number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Program to find the 1's complement of a binary number | |
def check_binary(num): | |
"""Returns true if the number is binary else, False""" | |
for i in str(num): | |
if i not in ('0', '1'): return False | |
return True | |
def find_one_complement(num): | |
"""Returns one's complement of the number""" | |
num_str = '' | |
for i in str(num): num_str += '1' if i == '0' else '0' | |
return num_str | |
# Take integer input | |
try: | |
number = int(input("Enter the number to check: ")) | |
except ValueError: | |
print("Please enter a positive integer: ") | |
number = int(input("Enter the number to check: ")) | |
if __name__ == "__main__": | |
# Check if the number is binary, and calculate its one's complement if so | |
if check_binary(number): print("1's complement of ", number, " is ", find_one_complement(number)) | |
else: print(number, " is not a binary number") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment