java中实现递归计算二进制表示中1的个数
借助Java语言,运用递归算法计算整数N的二进制表示中1的个数
/*usetherecursivealgorithmetocalculate
*thenumberof"1"inthebinaryexpression
*ofanIntegerN.
*Note:ifNisanodd,then
*theresultistheresultofN/2plus1.
*Andtheprogramusethebitoperationto
*improveefficency,thoughit'sseemingly
*notnecessary,buttheideaIthinkisgood.
*TheprogramiswritedbyZewangZhang,at
*2015-5-4,inSYSUdorms.
*/
publicclassCalculateNumberInBinaryExpression{
//Mainmethod.
publicstaticvoidmain(String[]args){
//Forexample,makeNequals13,theresultshows3
System.out.println(numOfEven(13));
//Forexample,makeNequals128,theresultshows1
System.out.println(numOfEven(128));
}
//ThestaticmethodofnumOfEvenistherecursivemethod.
publicstaticintnumOfEven(intx){
//Thebaseofrecursive.
if(x==0){
return0;
}
//Ifxisanodd.
elseif(x%2!=0){
returnnumOfEven(x>>1)+1;
}
//Ifxisanevenexcept0.
else{
while(x%2==0){
x=(x>>1);
}
returnnumOfEven(x);
}
}
}
来个最简单的,不过未测试:)
publicinta(inti){
if(i==0||i==1)returni;
returni%2+a(i/2);
}
以上所述就是本文的全部内容了,希望大家能够喜欢。