Tuesday, 7 September 2021
BinarySearch - Set Bits
[https://binarysearch.com/problems/Set-Bits](https://binarysearch.com/problems/Set-Bits)
## Problem
Given an integer n, return the total number of set bits in all integers between 1 and n inclusive.
Constraints
$ n ≤ 2 ^ {27} $
## Solution
The i-th least significant bit can be calculate as
$$ (\frac{n}{2 ^ i}) * 2 ^{i - 1} + n \bmod 2 ^ {i} - (2 ^ {i - 1} - 1) $$
if and only if
$$ n \bmod ( 2 ^ {i} ) >= (2 ^ {i - 1} - 1) $$
```
int solve(int n) {
    int two = 2, ans = 0;
    int tmp = n;
    while (tmp) {
        ans += (n / two) * (two >> 1);
        if ((n & (two - 1)) > (two >> 1) - 1) ans += (n & (two - 1)) - (two >> 1) + 1;
        two <<= 1, tmp >>= 1;
    }
    return ans;
}
```
Subscribe to:
Post Comments (Atom)
A Fun Problem - Math
# Problem Statement JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today t...
- 
SHA stands for Secure Hashing Algorithm and 2 is just a version number. SHA-2 revises the construction and the big-length of the signature f...
 - 
## SQRT Decomposition Square Root Decomposition is an technique optimizating common operations in time complexity O(sqrt(N)). The idea of t...
 
No comments:
Post a Comment