D - Bitmask Editorial by evima

Easier Implementation

If the number obtained by changing every ? in \(S\) to 0, the answer is -1. Otherwise, you can get the answer by doing the following for each digit that has been changed to 0, from top to bottom: “If changing that digit to 1 would not make the number exceed \(N\), change it to 1.”

Sample Implementation (Python)

S, N = list(reversed(input())), int(input())
s = 0
for i in range(len(S)):
    s |= (S[i] == '1') << i
if s > N:
    print(-1)
else:
    for i in reversed(range(len(S))):
        if S[i] == '?' and (s | 1 << i) <= N:
            s |= 1 << i
    print(s)

posted:
last update: