1

How to use the bit operations to find the number of units with running time O (k),

k - number of units in binary notation?

    int n, ans;
    cin >> n;
    while (n) {
        if (n & 1) {
            ans++;
        }
        n = (n >> 1);
    }
    cout << ans;

Time complexity of my solution is O(log n). But I need O(k).

1 Answers1

1

Number of units in binary notation = Number of set bits.

This is a familiar problem, you are looking for the Brian Kernighan’s Algorithm.

This algorithm works in O(log N), but also in O(K). In every iteration of the algorithm we unset the rightmost bit by performing n & (n - 1), therefore after K iterations the number will be 0 and we are done.

So time complexity is number of units (number of set bits), which is K.

Yonlif
  • 1,770
  • 1
  • 13
  • 31