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.