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