您的位置:首页 > 其它

计算一个数二进制中1的个数

2013-01-07 23:59 274 查看
Write a recursive method that returns the number of 1’s in the binary representation of N. Use the fact that is equal to the number of 1’s in therepresentation of N/2, plus 1, if N is odd.

根据要求可以知道题目是说的>=0的数,不然不符合恩

然后上代码
public class NumOfOne {
public static int calNum(int n){
if (n==1||n==2) {
return 1;
}else if (n==0) {
return 0;
}else{
if (n%2==0) {
return calNum(n/2);
}else{
return calNum(n-1)+1;
}
}
}
public static void main(String[]args){
System.out.println(calNum(7));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: