Java data structure and algorithm example: Fast computing the number of binary number 1 (Fast Bit counting) _java

Source: Internet
Author: User
/** 
 * Quickly calculates the number of 1 in a binary number (fast Bit counting) 
 * The idea of the algorithm is as follows: 
 * Each time you subtract the number from that number, the rightmost 1 is eliminated 
 * until the number is 0 
 * The number of intermediate loops is 1 of the number 
 * For example, given "10100", minus one after "10011", and "10000", which will eliminate the rightmost 1 
 * Sparse ones and dense ones were first Described by Peter Wegner in 
 * "a technique for counting ones in a Binary Computer", 
 * Communications of the ACM, Volume 3 (1960) Number 5, page 322 
 / 
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"); 
 } 
 /** 
  * @author * 
  @param i to be measured number 
  * @return binary representation of 1 of the number of * * Public 
 int getcount (int i) {   
  int n;
  for (n=0 i > 0; n++) { 
   i &= (i-1); 
  }   
  return n;   
 } 
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.