PHP Program to 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. PHP <?php // Function to get no of set // bits in binary representation // of positive integer n function countSetBits($n) { $count = 0; while ($n) { $count += $n & 1; $n >>= 1; } return $count; } // Driver Code $i = 9; echo countSetBits($i); // This code is contributed by ajit ?> Output: 2 Recursive Approach : PHP <?php // PHP implementation of recursive // approach to find the number of // set bits in binary representation // of positive integer n // recursive function // to count set bits function countSetBits($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 // get value from user $n = 9; // function calling echo countSetBits($n); // This code is contributed by m_kit. ?> Output: 2 Please refer complete article on Count set bits in an integer for more details! Like Article Suggest improvement Next PHP Program to Count Digits of a Number Share your thoughts in the comments Add Your Comment Please Login to comment... Similar Reads Program to swap two integer parameters using call by value & call by address in PHP ? PHP Program to Convert Integer to Roman Number JavaScript Program to Extract the Leftmost Set Bit of a Given Integer JavaScript Program to Extract the Rightmost set Bit of a Given Integer How to access an associative array by integer index in PHP? How to convert an Integer Into a String in PHP ? How to Increment by 1 to all the Digits of a given Integer in PHP ? JavaScript Program to Check if all Bits can be made Same by Single Flip JavaScript Program to Print All Distinct Elements in an Integer Array JavaScript Program to Find the Missing Number in a Given Integer Array of 1 to 100 Like GeeksforGeeks Article Tags : PHP Programs Web Technologies