Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 months ago
620 B
3
Indexable
Never
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;
}
Leave a Comment