Count set bits in an integer | Java implementation for recursive approach to find the number of set bits using Brian Kernighan Algorithm ; recursive function to count set bits ; base case ; Driver function ; get value from user ; function calling
import java . io . * ; class GFG { public static int countSetBits ( int n ) { if ( n == 0 ) return 0 ; else return 1 + countSetBits ( n & ( n - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 9 ; System . out . println ( countSetBits ( n ) ) ; } }