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. The position is counted from the right, starting at 1. In this article, we are going to discuss different approaches to solving this problem using C#.

Finding First Set Bit Position Number: 18 Binary: 1 0 0 1 0 5 4 3 2 1 First set bit at position 2

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.

Using an Iterative Approach

This is a straightforward approach where we iterate through the bits of the number from right to left and find the first set bit. This approach works well for most numbers and is simple to implement and debug.

Algorithm Steps

  • 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.

Example

using System;

class Program {
    static int FindFirstSetBitIterative(int num) {
        if (num == 0) return 0;
        
        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
    }

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

The output of the above code is

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

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

Using Bitwise Formula

This approach uses a direct bitwise formula to isolate the lowest set bit: position = log?(N & -N) + 1. The expression (N & -N) isolates the rightmost set bit, making this method very efficient.

Algorithm Steps

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

Example

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 num1 = 12;
        int num2 = 20;
        int num3 = 8;
        
        Console.WriteLine("The position of the first set bit in {0} is: {1}", num1, FindFirstSetBitFormula(num1));
        Console.WriteLine("The position of the first set bit in {0} is: {1}", num2, FindFirstSetBitFormula(num2));
        Console.WriteLine("The position of the first set bit in {0} is: {1}", num3, FindFirstSetBitFormula(num3));
    }
}

The output of the above code is

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

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 demonstrates the recursive problem-solving technique.

Algorithm Steps

  • 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.

Example

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 num1 = 20;
        int num2 = 16;
        
        Console.WriteLine("The position of the first set bit in {0} is: {1}", num1, FindFirstSetBitRecursive(num1));
        Console.WriteLine("The position of the first set bit in {0} is: {1}", num2, FindFirstSetBitRecursive(num2));
    }
}

The output of the above code is

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

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

Comparison of Approaches

Approach Time Complexity Space Complexity Best Use Case
Iterative O(log N) O(1) General purpose, easy to understand
Bitwise Formula O(1) O(1) Performance-critical applications
Recursive O(log N) O(log N) Learning recursion, small inputs

Real-Life Applications

  • Computer Networking: Used in error detection algorithms and network communication protocols.
  • Data Compression: Essential in run-length encoding and Huffman coding algorithms.
  • Cryptography: Bit manipulation operations are crucial in encryption algorithms and secure hashing functions.

Conclusion

Finding the first set bit position is a fundamental bit manipulation problem with multiple solution approaches. The iterative method offers simplicity, the bitwise formula provides optimal performance, and the recursive approach demonstrates algorithmic thinking. Choose the method based on your specific requirements for performance and code clarity.

Updated on: 2026-03-17T07:04:36+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements