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);
}
以上所述就是本文的全部内容了,希望大家能够喜欢。
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短