From f992b5eac63521fd7ff1327fe2c4d887030da533 Mon Sep 17 00:00:00 2001 From: USP-2024 <uspatil_b23@ce.vjti.ac.in> Date: Sun, 13 Oct 2024 19:43:04 +0530 Subject: [PATCH] Update binary_count_trailing_zeros.py The program prompts the user to enter a binary number. It checks if the input contains only 0s and 1s using a generator expression. If the input is valid, it calls the count_zeros_and_ones function and prints the results. If not, it notifies the user of the invalid input. --- .../binary_count_trailing_zeros.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/bit_manipulation/binary_count_trailing_zeros.py b/bit_manipulation/binary_count_trailing_zeros.py index f401c4ab9..702672e07 100644 --- a/bit_manipulation/binary_count_trailing_zeros.py +++ b/bit_manipulation/binary_count_trailing_zeros.py @@ -42,3 +42,25 @@ if __name__ == "__main__": import doctest doctest.testmod() + + +#counting number of 0s and 1s in a binary number +def count_zeros_and_ones(binary_number): + # Convert the binary number to a string if it's not already + binary_str = str(binary_number) + + count_zeros = binary_str.count('0') + count_ones = binary_str.count('1') + + return count_zeros, count_ones + +# Get user input +binary_number = input("Enter a binary number: ") + +# Validate input +if all(bit in '01' for bit in binary_number): + zeros, ones = count_zeros_and_ones(binary_number) + print(f"Number of 0s: {zeros}, Number of 1s: {ones}") +else: + print("Invalid input! Please enter a valid binary number.") +