freq
with a size large enough to hold all possible powers of 2.freq
with the count of each power of 2 present in nums
.res
to 0, which will hold the result.target
from 0 to 31 (since target
is an integer and has at most 32 bits).target
, check if freq[i]
is greater than 0.freq[i]
is greater than 0, decrement it by 1.freq[i]
is 0, find the next j
where freq[j]
is greater than 0, decrement freq[j]
by 1, increment res
by j-i
, and increment freq[k]
for all k
from i
to j-1
.freq[i]
to freq[i+1]
.res
as the result.