881893. Set bits in N

Basic

Set bits in N

Summary

Given a positive integer N, write an algorithm to count the number of set bits (bits that are equal to 1) in the binary representation of N. This problem involves understanding the concept of bitwise operations and manipulation.

Detailed Explanation

To solve this problem, we can use a simple bitwise operation. The idea is to use the bitwise AND operator (&) to find the set bits in the binary representation of N.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable set_bits to 0.
  2. Loop through each bit in the binary representation of N, starting from the least significant bit (rightmost) to the most significant bit (leftmost).
  3. For each bit, use the bitwise AND operator (&) with the current bit and the number 1. This will give us a result that is either 0 (if the bit is not set) or 1 (if the bit is set).
  4. If the result is non-zero, increment set_bits by 1.
  5. After looping through all bits, return the value of set_bits.

Here's an ASCII art diagram to illustrate this process:

    N: 11001010
    ^         ^
    |         |
    v         v
  1 & 1 = 1  // set bit
  0 & 1 = 0  // not a set bit
  ...
  0 & 1 = 0  // not a set bit

Time complexity: O(log N) (where N is the input integer) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int countSetBits(int n) {
    int set_bits = 0;
    while (n > 0) {
        if ((n & 1) == 1) {
            set_bits++;
        }
        n >>= 1;
    }
    return set_bits;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.