Counting the Number of 1 Bits in an Unsigned Integer

Counting the Number of 1 Bits in an Unsigned Integer

In the world of computer programming, binary representations of numbers are fundamental.

A common problem that arises is counting how many bits are set to 1 in the binary form of a given number. In this article, we will explore how to solve this problem efficiently.

Pair with given sum - Two Sum

Problem Overview

You are given an unsigned integer n. The task is to count the number of 1 bits in its binary representation. The number n is non-negative and fits within a 32-bit unsigned integer, meaning it is guaranteed to be a valid number in the range from 0 to 4,294,967,295.

The binary representation of a number is simply its equivalent expression in base-2, where each digit (bit) can either be a 0 or a 1. Our goal is to count how many 1 bits there are in the binary representation of n.

Understanding the Input and Output

  • Input: An unsigned integer n, which fits within 32-bits.
  • Output: The number of 1 bits in the binary representation of n.

Example Walkthrough

Let’s break down a couple of examples to understand the problem better.

This is the binary representation of the integer 23:

Binary: 00000000000000000000000000010111
Number of 1 bits: There are 4 ones in this binary number.

This is the binary representation of the integer 2147483645:

Binary: 01111111111111111111111111111101
Number of 1 bits: There are 30 ones in this binary number.

Approach to Solving the Problem

The task can be solved in several ways, but the most efficient method is to use bit manipulation. Here’s a step-by-step approach:

  1. Right Shift and Check Each Bit:

    • We can iterate through each bit of the integer, checking whether it is 1 or 0.
    • We do this by repeatedly shifting the number to the right and checking the least significant bit (the rightmost bit).
  2. Using Bitwise AND:

    • A simple way to check if a bit is 1 is to use the bitwise AND operation with 1. If the result is 1, then the bit is 1, otherwise, it is 0.
    • Example: n & 1 will return 1 if the least significant bit of n is 1, and 0 if it is 0.
  3. Continue Shifting:

    • After checking the least significant bit, shift the number right by one bit (n >>= 1) to examine the next bit.
    • Repeat this process until the number becomes 0, meaning we’ve checked all bits.

There are mainly 4 approach to solve this problem – 

  1. Bit Mask – I Method
  2. Bit Mask – II Method 
  3. Bit Mask (Optimal)
  4. Built In Function

1. Bit Mask – I

Time & Space Complexity
  • Time complexity: O(1)
  • Space complexity: O(1)

2. Bit Mask – II

Time & Space Complexity
    • Time complexity: O(1)
    • Space complexity: O(1)

Code

3. Bit Mask (Optimal)

  • Time complexity: O(1)
  • Space complexity: O(1)

Code

4. Built-In Function

Time & Space Complexity

  • Time complexity: O(1)
  • Space complexity: O(1)

Code

More Articles