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 婆婆高寿祝福语大全简短