Update binary_count_trailing_zeros.py

The function count_zeros_and_ones takes a binary number as input.
It converts the number to a string and counts the occurrences of 0 and 1 using the count() method.
It returns the counts, which are then printed out.
You can replace binary_number with any binary number you'd like to analyze!
This commit is contained in:
USP-2024 2024-10-13 20:07:18 +05:30 committed by GitHub
parent 103d7c48cb
commit ab7bcb99bc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -48,19 +48,14 @@ if __name__ == "__main__":
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")
count_zeros = binary_str.count('0')
count_ones = binary_str.count('1')
return count_zeros, count_ones
# Example usage
binary_number = 1011001
zeros, ones = count_zeros_and_ones(binary_number)
print(f"Number of 0s: {zeros}, Number of 1s: {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.")