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

来源:互联网 发布:程序员女装梗 编辑:程序博客网 时间:2024/05/27 20:05

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));}}

原创粉丝点击