Minimum Number of K Consecutive Bit Flips
Question
What is the minimum number of consecutive bit flips required to convert an integer from binary to its complement?
Example 1
Input: A = [0,1,0], K = 2
Output: 2
Solution
- ▭
- ▯
all//Minimum Number of K Consecutive Bit Flips.py
def minKBitFlips(string, k):
flips = 0
for i in range(len(string) - k + 1):
if string[i] == '0':
for j in range(k):
string[i + j] = '1' if string[i + j] == '0' else '0'
flips += 1
return flips if all(x == '1' for x in string) else -1
string = list("000101")
k = 3
print(minKBitFlips(string, k))
all//Minimum Number of K Consecutive Bit Flips.py
def minKBitFlips(string, k):
flips = 0
for i in range(len(string) - k + 1):
if string[i] == '0':
for j in range(k):
string[i + j] = '1' if string[i + j] == '0' else '0'
flips += 1
return flips if all(x == '1' for x in string) else -1
string = list("000101")
k = 3
print(minKBitFlips(string, k))