题目
整数的二进制表达中有多少个1
package com.lizhouwei.chapter7;
/**
* @Description: 整数的二进制表达中有多少个1
* @Author: lizhouwei
* @CreateDate: 2018/4/26 21:46
* @Modify by:
* @ModifyDate:
*/
public class Chapter7_4 {
public int count(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
//测试
public static void main(String[] args) {
Chapter7_4 chapter = new Chapter7_4();
System.out.println("4的二进制中有:"+chapter.count(4)+"个1");
System.out.println("3的二进制中有:"+chapter.count(3)+"个1");
System.out.println("15的二进制中有:"+chapter.count(15)+"个1");
}
}
结果