C# Program for Count set bits in an integer Last Updated : 02 Jan, 2019 Improve Improve Like Article Like Save Share Report Write an efficient program to count number of 1s in binary representation of an integer. Examples : Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 13 Output : 3 Binary representation of 11 is 1101 and has 3 set bits Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. 1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program. C# // C# program to Count set // bits in an integer using System; class GFG { // Function to get no of set // bits in binary representation // of positive integer n static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Driver Code public static void Main() { int i = 9; Console.Write(countSetBits(i)); } } // This code is contributed by Sam007 Output: 2 Recursive Approach : C# // C# implementation of recursive // approach to find the number of // set bits in binary representation // of positive integer n using System; class GFG { // recursive function // to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else // if last bit set // add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } // Driver code static public void Main() { // get value // from user int n = 9; // function calling Console.WriteLine(countSetBits(n)); } } // This code is contributed by aj_36 Output: 2 Please refer complete article on Count set bits in an integer for more details! Like Article Suggest improvement Previous C# Program to find whether a no is power of two Next C# Program for Median of two sorted arrays of same size Share your thoughts in the comments Add Your Comment Please Login to comment... Similar Reads C# Program to Rotate bits of a number C# Program to Convert the Octal String to an Integer Number C# Program to Convert a Binary String to an Integer C# Program for Converting Hexadecimal String to Integer C# Program to Find Integer Numbers from the List of Objects and Sort them Using LINQ C# Program for Count Inversions in an array | Set 1 (Using Merge Sort) Different ways to convert String to Integer in C# C# Program for Count ways to reach the n\'th stair C# Program to Count trailing zeroes in factorial of a number C# Program to Count the Files Based on Extension using LINQ Like GeeksforGeeks Article Tags : C# Programs