Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check whether a number has consecutive 0's in the given base or not using Python
When working with different number bases, we sometimes need to check if a number contains consecutive zeros in its representation. Python provides an efficient way to convert numbers between bases and detect patterns like consecutive zeros.
Understanding the Problem
For example, the number 8 in base 2 (binary) is represented as "1000", which contains consecutive zeros. We need to convert the number to the specified base and then check for consecutive zero digits.
Complete Solution
def check_consecutive_zero(N, K):
my_result = convert_to_base(N, K)
if (check_consecutive_zeros(my_result)):
print("Yes")
else:
print("No")
def convert_to_base(N, K):
weight = 1
s = 0
while (N != 0):
r = N % K
N = N // K
s = r * weight + s
weight *= 10
return s
def check_consecutive_zeros(N):
prev_zero = False
while (N != 0):
r = N % 10
N = N // 10
if (prev_zero == True and r == 0):
return True
if (r > 0):
prev_zero = False
continue
prev_zero = True
return False
# Test the function
N, K = 8, 2
print("Does the number have consecutive zeroes in the base?")
check_consecutive_zero(N, K)
# Additional test cases
print("\nTesting with different numbers:")
test_cases = [(12, 2), (15, 3), (20, 4)]
for num, base in test_cases:
print(f"Number {num} in base {base}:", end=" ")
check_consecutive_zero(num, base)
Does the number have consecutive zeroes in the base? Yes Testing with different numbers: Number 12 in base 2: Yes Number 15 in base 3: No Number 20 in base 4: Yes
How It Works
The solution works in three steps:
-
Base Conversion: The
convert_to_base()function converts a decimal number to the specified base representation -
Zero Detection: The
check_consecutive_zeros()function examines each digit to find consecutive zeros - Result Display: The main function coordinates the process and displays the result
Example Breakdown
Let's trace through the example where N=8 and K=2:
# Converting 8 to base 2
# 8 ÷ 2 = 4 remainder 0
# 4 ÷ 2 = 2 remainder 0
# 2 ÷ 2 = 1 remainder 0
# 1 ÷ 2 = 0 remainder 1
# Result: 1000 (reading remainders bottom to top)
number = 8
base = 2
converted = convert_to_base(number, base)
print(f"Number {number} in base {base} is: {converted}")
# Check for consecutive zeros in 1000
# We find three consecutive zeros
Number 8 in base 2 is: 1000
Conclusion
This approach efficiently converts numbers to any base and detects consecutive zeros by tracking the previous digit state. The algorithm works for any base greater than 1 and handles edge cases properly.
