C# Program to Find First Set Bit



In this problem, we are given a number n, and we need to find the position of the first set bit (1-bit) in its binary representation. In this article, we are going to discuss different approaches to solving this problem using C#.

Example 1

  • Input: N = 18
  • Output: 2

Explanation:

The binary representation of 18 is 10010. The first set bit from the right is at position 2.

Example 2

  • Input: N = 12
  • Output: 3

Explanation:

The binary representation of 12 is 1100. The first set bit from the right is at position 3.

Below are different approaches to finding the first set bit.

Using an Iterative Approach

This is a straightforward and simple approach where we iterate through the bits of the number and find the first set bit. This approach works well for small numbers, but for very large numbers it involves multiple iterations. This approach is simple to implement and easy to debug.

Steps for Implementation

  • Initialize position = 1.
  • Iterate while num is greater than 0.
  • Check if the least significant bit is set using (num & 1) == 1.
  • If found, return position.
  • Right shift num by 1 (num >>= 1) and increment position.
  • If no set bit is found, return 0.

Implementation Code

using System;

class Program {
  static int FindFirstSetBitIterative(int num) {
    int position = 1;
    while (num > 0) {
      if ((num & 1) == 1)
        return position; // Return the first position where a set bit is found
      
      num >>= 1;
      position++;
    }
    return 0; // No set bit found (for num = 0)
  }

  static void Main() {
    int num = 18;
    int result = FindFirstSetBitIterative(num);
    Console.WriteLine("The position of the first set bit in {0} is: {1}", num, result);
  }
}

Output:

The position of the first set bit in 18 is: 2

Time Complexity: O(log N)
Space Complexity: O(1)

Using Bitwise Formula

This approach reduces the number of iterations by using a direct bitwise formula. We use: position = log2( N & - N) + 1. This approach avoids loops, which makes it preferable for performance-critical applications. However, it requires logarithm computation, which may introduce minor precision issues in many environments.

Steps for Implementation

  • If num is 0, return 0 (no set bit found).
  • Compute (num & -num) to isolate the lowest set bit.
  • Apply log2 function and add 1 to get the position.

Implementation Code

using System;

class Program {
    static int FindFirstSetBitFormula(int num) {
        if (num == 0) return 0;
        return (int)(Math.Log(num & -num, 2)) + 1; // Use Math.Log with base 2
    }

    static void Main() {
        int num = 12;
        int result = FindFirstSetBitFormula(num);
        Console.WriteLine("The position of the first set bit in {0} is: {1}", num, result);
    }
}

Output:

The position of the first set bit in 12 is: 3

Time Complexity: O(1)
Space Complexity: O(1)

Using Recursive Approach

In this approach, we use recursion to check each bit position until we find the first set bit. This method is useful for learning but can cause stack overflow for very large numbers due to deep recursion. This method is best for small inputs where function call overhead is minimal.

Steps for Implementation

  • If num is 0, return 0 (no set bit found).
  • Check if the least significant bit is set using (num & 1) == 1.
  • If found, return position.
  • Otherwise, call the function recursively with num >> 1 and position + 1.

Implementation Code

using System;

class Program {
  static int FindFirstSetBitRecursive(int num, int position = 1) {
    if (num == 0)
      return 0; // If number is 0, return 0 (no set bit found)
    if ((num & 1) == 1)
      return position; // Return position if set bit is found
    return FindFirstSetBitRecursive(num >> 1, position + 1);
  }

  static void Main() {
    int num = 20;
    int result = FindFirstSetBitRecursive(num);
    Console.WriteLine("The position of the first set bit in {0} is: {1}", num, result);
  }
}

Output:

The position of the first set bit in 20 is: 3

Time Complexity: O(log N)
Space Complexity: O(log N) (due to recursion)

Real-Life Applications

  • Computer Networking: It can be used in error detection and network communication protocols.
  • Data Compression: It is used to find the first set bit and is useful in run-length encoding and Huffman coding.
  • Cryptography: Bit manipulation plays a crucial role in encryption algorithms and secure hashing.
Updated on: 2025-03-20T13:01:10+05:30

678 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements