簡體   English   中英

有多少種方法可以替換字符串中的 0?

[英]How many ways can I replace the 0 in a string?

我們說 integer A 符合 integer B 如果在 B 的所有位設置為 1 的位置,A 對應的位設置為 1。例如:

00 0000 1111 0111 1101 1110 0000 1111(BIN) = 16,244,239 conforms to
00 0000 1100 0110 1101 1110 0000 0001(BIN) = 13,032,961, but
11 0000 1101 0111 0000 1010 0000 0101(BIN) = 819,399,173 does not conform to
00 0000 1001 0110 0011 0011 0000 1111(BIN) = 9,843,471.

即,給定三個無符號 30 位整數 A、B 和 C,返回符合給定整數中的至少一個的無符號 30 位整數的數量。

例如,對於整數:

A = 11 1111 1111 1111 1111 1111 1001 1111(BIN) = 1,073,741,727,
B = 11 1111 1111 1111 1111 1111 0011 1111(BIN) = 1,073,741,631, and
C = 11 1111 1111 1111 1111 1111 0110 1111(BIN) = 1,073,741,679,

function 應該返回 8,因為有 8 個符合 A、B 或 C 的無符號 30 位整數,即:

11 1111 1111 1111 1111 1111 0011 1111(BIN) = 1,073,741,631,
11 1111 1111 1111 1111 1111 0110 1111(BIN) = 1,073,741,679,
11 1111 1111 1111 1111 1111 0111 1111(BIN) = 1,073,741,695,
11 1111 1111 1111 1111 1111 1001 1111(BIN) = 1,073,741,727,
11 1111 1111 1111 1111 1111 1011 1111(BIN) = 1,073,741,759,
11 1111 1111 1111 1111 1111 1101 1111(BIN) = 1,073,741,791,
11 1111 1111 1111 1111 1111 1110 1111(BIN) = 1,073,741,807,
11 1111 1111 1111 1111 1111 1111 1111(BIN) = 1,073,741,823.

目標

def solution(A,B,C):
   ...
   return number_of_compinations

這是一個適用於 3 個數字的 function:

def zero_count(n,k):
    return bin(n)[2:].zfill(k).count('0')

def count_extensions(a,b,c,k):
    #include individual items
    s = 2**zero_count(a,k)
    s += 2**zero_count(b,k)
    s += 2**zero_count(c,k)

    #exclude pairs
    s -= 2**zero_count(a|b,k)
    s -= 2**zero_count(a|c,k)
    s -= 2**zero_count(b|c,k)

    #include all 3:
    s += 2**zero_count(a|b|c,k)
    return s

a = 1073741727
b = 1073741631
c = 1073741679

print(count_extensions(a,b,c,30)) #8

它使用 3-set 包含-排除原則 如果您想推廣到 3 個以上的數字,則需要完整的原則。

您可以這樣做:

在數字之間使用按位 &。 然后計算結果中1的個數:

a = 8
b = 7

c = a&b

strc = bin(c)[2:] #remove 0b at the begining of the string

# count 1
print(strc.count("1"))
# prints 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM