從LSB到MSB的工作,您有運行的設置位被清除位的運行分隔:間隙。
(沒有攜帶 在)每個單1
會變成 11
- 「多顯著 1
」在那裏有個地方一個零之前:沒有 進行 了。
如果您將10
添加到長期運行的1
s並清除最不重要的位,您將得到原始數字的三倍的二進制表示 - 具有完全相同的位數設置。並且1
其中可能是是下一個,err,以及1
:a 進位 進出。任何進行 in被吸收:它只是「交換」最低有效位。
與表示三次單個 1
的11
,一個攜帶 在導致攜帶 出 - 並清除兩個比特(嘗試用101011
* 3)。
長度超過一個「吸收」的間隙進行。
假設輸入指數按照升序排序,或者用O(n)算法使我驚喜。我很想用標籤來編寫一個狀態機。
因爲我練的Python:
def popcount3num(indices):
'''
given, in (strictly) ascending order, the indices of bits set
in the binary representation of a natural number num,
return the number of bits set in 3*num
'''
prev = -3 # position of last bit handled
count = carry = 0 # carry is for bitposition handled + 2
for i in indices:
# print(i, count, carry)
if prev == i-1: # in a run of set bits
if not carry:
carry = 1 # "move bit from count to carry"
count -= 1
else:
count += 1 # tally
else: # gap
if not carry:
# without a carry in, every run produces
# two bits at least, including carry out
count += 2
elif prev < i-2:
# if the carry was for a lower position, just tally
count += 3
carry = 0
else:
# with a carry in, a lone one will change nothing
# a run will add just as many as without carry
pass
prev = i
return count + carry
IMO直覺是正確的:從正確的工作(LSB)到左(MSB),而加入攜帶。 – wildplasser
這正是我的想法,但它有點棘手。考慮數字5 - 數組是[0,2]。結果你應該得到4。然後考慮7 - 數組是[0,1,2],結果爲3. – Marcus
我想澄清。如果num = 5(arr5 = [0,2],是3 * 5 = 15(arr15 = [0,1,2,3])你想要什麼? – Ripi2