Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to count total set bits in a number
A set bit refers to a bit that has a value of 1 in the binary representation of a number. Counting set bits is a common programming problem that involves examining each bit position to determine how many are set to 1.
For example, the number 11 in decimal has the binary representation 1011, which contains 3 set bits (three 1s).
Approach
The most straightforward approach uses bitwise operations to examine each bit −
-
Use the bitwise AND operator (
&) with 1 to check if the least significant bit is set -
Right-shift the number by 1 bit to examine the next bit
-
Continue until the number becomes 0
Using Bitwise Operations
Example
using System;
public class Demo {
public static void Main() {
int count = 0;
int num = 11; // Binary: 1011
Console.WriteLine("Number: " + num);
Console.WriteLine("Binary: " + Convert.ToString(num, 2));
while (num > 0) {
count += num & 1; // Check if LSB is 1
num >>= 1; // Right shift by 1
}
Console.WriteLine("Total set bits: " + count);
}
}
The output of the above code is −
Number: 11 Binary: 1011 Total set bits: 3
Using Built-in Method
.NET provides a built-in method PopCount in the BitOperations class for counting set bits −
Example
using System;
using System.Numerics;
public class Demo {
public static void Main() {
int num = 11;
Console.WriteLine("Number: " + num);
Console.WriteLine("Binary: " + Convert.ToString(num, 2));
int setBits = BitOperations.PopCount((uint)num);
Console.WriteLine("Total set bits: " + setBits);
}
}
The output of the above code is −
Number: 11 Binary: 1011 Total set bits: 3
Brian Kernighan's Algorithm
This optimized approach eliminates trailing zeros by using the property that n & (n-1) removes the rightmost set bit −
Example
using System;
public class Demo {
public static void Main() {
int count = 0;
int num = 11; // Binary: 1011
Console.WriteLine("Number: " + num);
Console.WriteLine("Binary: " + Convert.ToString(num, 2));
while (num > 0) {
count++;
num = num & (num - 1); // Remove rightmost set bit
}
Console.WriteLine("Total set bits: " + count);
}
}
The output of the above code is −
Number: 11 Binary: 1011 Total set bits: 3
Comparison
| Method | Time Complexity | Description |
|---|---|---|
| Bitwise Operations | O(log n) | Checks every bit position |
| Brian Kernighan's | O(set bits) | Only iterates through set bits |
| Built-in PopCount | O(1) | Hardware-optimized operation |
Conclusion
Counting set bits can be accomplished using bitwise operations, Brian Kernighan's algorithm for optimization, or built-in methods like BitOperations.PopCount. The choice depends on performance requirements and .NET version compatibility.
