[英]How to find minNumber of operations such that binary string of length N is all zeros?
如何找到 minNumber 的操作,使得長度為 N 的二進制字符串全為零?
選擇兩個相鄰的字符並用它們的異或值替換它們。
例如取二進制字符串“101”
選擇第一個和第二個和 xor => 111
選擇第一個和第二個和 xor => 001
選擇第 2 和第 3 和 xor => 011
選擇第 2 和第 3 和 xor => 000
所以最小操作數是 4
這是我的嘗試
def checkAllZeros(astr):
for each_char in astr:
if each_char == 1:
return False
return True
def getMinOperations(astr):
totalOps = 0
while checkAllZeros(astr):
i = 0
j = 1
if j < len(astr):
if (astr[i] == '0' and astr[j] == '1') or (astr[i] == '1' and astr[j] == '0'):
astr = astr[0:i] + '11' + astr[i + 2:]
totalOps += 1
elif astr[i] == '1' and astr[j] == '1':
astr = astr[0:i] + '00' + astr[i + 2:]
totalOps += 1
i += 1
j += 1
else:
i += 1
j += 1
if __name__ == '__main__':
print(getMinOperations('1111'))
我假設這需要動態編程? 不知何故,它不適用於大弦
更新:
我們可以這樣分解:
'00' -> 0(次)
'01' -> 2
'10' -> 2
'11' -> 1
所以答案可能是這樣的:
astr = '1101010010111'
operations = 0
operations += astr.count('11')
astr = astr.replace('11', '')
operations += sum(list(map(int, astr))) * 2
print(operations) # 10
如何定義“操作”?
例如:
astr = '110111'
sumOne = sum(list(map(int, astr)))
operations = sumOne // 2 + sumOne % 2
print(operations) # 3
選擇第一個和第二個和 xor => 000111
選擇第 4 和第 5 和 xor => 000001
選擇第 5 和第 6 並且 => 000000
所以最小操作數是 3
問題是是否使用“操作”找到“1”的索引
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.