Problem · Bit Manipulation
Count Numbers with the Same Set-Bit Count
Learn this problemProblem statement
You are given a positive integer n. Define f(n) as the smallest integer greater than or equal to n whose binary representation consists entirely of 1 bits.
Count the positive integers x that satisfy all of the following conditions:
x <= f(n)x != nxandncontain the same number of set bits in their binary representations
Return the count modulo 1,000,000,007.
Complete countSameBitNumbers for the given integer n.
Function
countSameBitNumbers(n: int) → intExamples
Example 1
n = 6return = 2f(6) = 7, whose binary representation is 111. The integers other than 6 with two set bits and at most 7 are 3 (011) and 5 (101).
Example 2
n = 10return = 5f(10) = 15. Among the six four-bit patterns containing two set bits, one represents n itself, so five other integers qualify.
Example 3
n = 7return = 0The only positive integer at most 7 with three set bits is 7, which must be excluded.
Constraints
0 < n < 2^31