PHP Program to Count set bits in an integer
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 ?> |
chevron_right
filter_none
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. ?> |
chevron_right
filter_none
Output:
2
Please refer complete article on Count set bits in an integer for more details!
Recommended Posts:
- Program to remove empty array elements in PHP
- Program to Insert new item in array on any position in PHP
- PHP Program for Naive algorithm for Pattern Searching
- PHP Program for Rabin-Karp Algorithm for Pattern Searching
- PHP Program to print all permutations of a given string
- PHP Program for Median of two sorted arrays of same size
- PHP Program for Subset Sum Problem | DP-25
- PHP Program for Largest Sum Contiguous Subarray
- PHP Program for Minimum number of jumps to reach end
- PHP Program for Cutting a Rod | DP-13
- PHP Program for Longest Palindromic Subsequence | DP-12
- PHP Program for Egg Dropping Puzzle | DP-11
- PHP Program to Find the Number Occurring Odd Number of Times
- PHP Program to Count number of binary strings without consecutive 1's
- PHP Program for Count ways to reach the n\'th stair