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 入住酒店文案祝福语简短