Examples of Java data structures and algorithms: quickly count the number of 1's in binary Numbers of Fast Bit Counting

  • 2020-04-01 03:56:53
  • OfStack


 
package al; 
public class CountOnes { 
 public static void main(String[] args) { 
  int i = 7; 
  CountOnes count = new CountOnes(); 
  System.out.println("There are " + count.getCount(i) + " ones in i"); 
 } 
  
 public int getCount(int i) {   
  int n; 
  for(n=0; i > 0; n++) { 
   i &= (i - 1); 
  }   
  return n;   
 } 
}


Related articles: