714515. Count Total Setbits

Medium

Count Total Setbits

Slug: count-total-setbits

Difficulty: Medium

Id: 714515

Topic Tags: Bit Magic, Data Structures, Algorithms

Company Tags: None

Summary

This problem requires you to write a function that counts the total number of set bits in all numbers from 1 to N. A set bit is a bit that has a value of 1. For example, the binary representation of 9 (which is 1001) has two set bits.

Detailed Explanation

To solve this problem, we can use a simple approach by iterating over each number from 1 to N and counting the set bits for each number. We can do this using bitwise operations. Specifically, we can use the expression n & (n - 1) to count the number of set bits in n. This works because the leftmost set bit will be shifted to the right when we subtract 1 from n, and all other bits will remain unchanged.

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

  1. Initialize a variable setbits to 0, which will store the total number of set bits.
  2. Iterate over each number i from 1 to N.
  3. For each number i, count the number of set bits using the expression i & (i - 1). This gives us the number of set bits in i.
  4. Add this count to the total setbits variable.
  5. Return the total setbits variable.

Here's a time complexity analysis: O(N), where N is the input size. We need to iterate over each number from 1 to N, so the time complexity is linear.

Here's a space complexity analysis: O(1). We only need a constant amount of space to store the total setbits variable, so the space complexity is constant.

Optimized Solutions

Java

View on GeeksforGeeks
public int countTotalSetBits(int n) {
    int setbits = 0;
    for (int i = 1; i <= n; i++) {
        setbits += Integer.bitCount(i);
    }
    return setbits;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.