Look up method\ Brian kerningam's method and a naive method for counting set bits GFG

 package com.company;


class CWR_BitMagic_Gfg{

static int[] table = new int[256];

// recursive function to count set bits
public static void initialize() {

// To initially generate the table algorithmically:
table[0] = 0;
for (int i = 0; i < 256; i++) {
table[i] = (i & 1) + table[i / 2];
}
}

public static int countSetBits(int n) {
return table[n & 0xff] +
table[(n >> 8) & 0xff] +
table[(n >> 16) & 0xff] +
table[n >> 24];
}

// Driver function
public static void main(String[] args) {
initialize(); // important point********************************
int n = 9;
System.out.println(countSetBits(n));
}
}

// static int [] table = new int [256];
// // My method
// public static int countBits(int n) {
// int count = 0;
// for (int i = 1; i <= 32; i++) {
// if ((n & (1 << (i - 1))) != 0) {
// count++;
// }
// }
// return count;
// }
//
// // Naive solution
// public static int count1(int n) {
// int res = 0;
// while (n > 0) {
// if ((n & 1) == 1) {
// res++;
// n = n / 2;
// }
// }
// return res;
// }
//
// // Brian kerningam's algorithm
// public static int count2(int n) {
// int res = 0;
// while (n > 0) {
// n = (n & (n - 1));
// res++;
// }
// return res;
// }
//
//// Lookup table method
// public static void initialize(){
// table[0] = 0;
// for(int i = 0; i<256; i++){
// table[i] = (i&1) + table[i/2];
// }
//// for (int e:table) {
//// System.out.println(e);
// }
//
//
// public static int count3(int n){
//
// return table[n & 0xff] +
// table[(n >> 8) & 0xff] +
// table[(n >> 16) & 0xff] +
// table[n >> 24];
// }

// public static void main(String[] args) {
//
//// System.out.println(countBits(40));
//// System.out.println(count1(7));
//// System.out.println(count3(7));
//// initialize();
// }
//}

Comments