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 红包祝福语简短10字
18 周六早晨祝福语简短