Problem Link

Description


You are given an integer k and an integer x. The price of a number num is calculated by the count of set bits at positions x, 2x, 3x, etc., in its binary representation, starting from the least significant bit. The following table contains examples of how price is calculated.

xnumBinary RepresentationPrice
1130000011013
2130000011011
22330111010013
3130000011011
33621011010102

The accumulated price of num is the total price of numbers from 1 to num. num is considered cheap if its accumulated price is less than or equal to k.

Return the greatest cheap number.

 

Example 1:

Input: k = 9, x = 1

Output: 6

Explanation:

As shown in the table below, 6 is the greatest cheap number.

xnumBinary RepresentationPriceAccumulated Price
1100111
1201012
1301124
1410015
1510127
1611029
17111312

Example 2:

Input: k = 7, x = 2

Output: 9

Explanation:

As shown in the table below, 9 is the greatest cheap number.

xnumBinary RepresentationPriceAccumulated Price
21000100
22001011
23001112
24010002
25010102
26011013
27011114
28100015
29100116
210101028

 

Constraints:

  • 1 <= k <= 1015
  • 1 <= x <= 8

Solution


Python3

class Solution:
    def findMaximumNumber(self, k: int, x: int) -> int:
        
        def good(num):
            price = 0
 
            for bit in range(x, num.bit_length() + 1, x):
                b = bit + 1
                groupSize = 2 ** (bit)
                groupOnes = 2 ** (bit - 1)
 
                ones = (num // groupSize) * groupOnes
                rem = max(0, (num % groupSize) - groupOnes)
 
                price += ones + rem
            
            return price <= k
        
        left, right = 0, 10 ** 20
        while left < right:
            mid = (left + right + 1) // 2
            
            if good(mid):
                left = mid
            else:
                right = mid - 1
        
        return left - 1