《数据结构与算法分析 Java语言描述》练习1.5
编写一种递归方法,它返回数N的二进制表示中1的个数。利用这样的事实:如果N是奇数,那么其1的个数等于N/2的二进制表示中1的个数加1。
public class Practice1_5 {
public static int countTheNumberOf1(int n) {
int count = 0;
int n1 = n;
while (n1 > 0) {// 计算数中1的个数
if ((n1 & 1) == 1) {
count++;
}
n1 = n1 >> 1;
}
if (count % 2 != 0) {
count = countTheNumberOf1_odd(n / 2);
}
return count;
}
public static int countTheNumberOf1_odd(int n) {// 如果N是奇数,则调用此函数
int count = 1;
int n1 = n;
while (n1 > 0) {
if ((n1 & 1) == 1) {
count++;
}
n1 = n1 >> 1;
}
if (count % 2 != 0) {
count = countTheNumberOf1_odd(n / 2);
}
return count;
}
public static void main(String[] args) {
Practice1_5 p = new Practice1_5();
int count = p.countTheNumberOf1(1024);
System.out.println(count);
}
}