Untitled
unknown
c_cpp
a year ago
1.1 kB
11
Indexable
class Solution { public: using ll = long long; long long countSetBitsAtPosition(long long n, int i) { if (n < 0) return 0; // Use unsigned long long to avoid negative overflow issues unsigned long long uln = static_cast<unsigned long long>(n); unsigned long long cycleLength = 1ULL << (i + 1); unsigned long long completeCycles = uln / cycleLength; unsigned long long setBitsCount = completeCycles * (cycleLength / 2); unsigned long long remainingNumbers = uln % cycleLength; if (remainingNumbers >= cycleLength / 2) { setBitsCount += remainingNumbers - (cycleLength / 2) + 1; } return setBitsCount; } ll helper(ll m, ll x){ ll cnt = 0; for(int i = x; i < 64; i += x){ cnt += countSetBitsAtPosition(m, i-1); } return cnt; } long long findMaximumNumber(long long k, int x) { ll l = 0, r = 1e15+1; while(l+1 != r){ ll m = l + (r-l)/2; if(helper(m, x) > k) r = m; else l = m; } return l; } };
Editor is loading...
Leave a Comment