The number of 1 in the binary representation of recursive computation in Java _java

Source: Internet
Author: User

Using the Java language, recursive algorithms are used to compute the number of 1 in the binary representation of an integer n

/*use the recursive Algorithme to calculate * The number of "1" in the binary expression * of the Integer N.
 * Note:if N is a odd, then * The result was the result of N/2 plus 1. * and the program with the bit operation to * improve efficency, though it's seemingly * not necessary, but the idea I th
 Ink is good.
 * The program are writed by Zewang Zhang and at * 2015-5-4,in SYSU dorms.
  */public class Calculatenumberinbinaryexpression {//main method. public static void Main (string[] args) {//for example, make N equals, the result shows 3 System.out.prin
     
    TLN (Numofeven (13));
  For example, make N equals 128, the result shows 1 System.out.println (Numofeven (128));
  //the static method of Numofeven is the recursive method.
    public static int Numofeven (int x) {//the base of recursive.
    if (x==0) {return 0;
    }//if x is a odd.
    else if (x%2!=0) {return Numofeven (x>>1) +1; }//if X is a even except 0.
      else {while (x%2==0) {x= (x>>1);
    return Numofeven (x);
 }
  }
}

One of the simplest, but not tested:

public int A (int i) {
    if (i==0| | I==1) return i;
    Return I%2+a (I/2);

}

The above mentioned is the entire content of this article, I hope you can enjoy.

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.