/**
* 给定一个整数,求它的二进制表示中有多少个1
*/
public class CountOne {

public static void main(String[] args) {
int n = 1021;
countOne1(n);
countOne2(n);
countOne3(n);
countOne4(n);
}

private static void countOne1(int n) {
int count = 0;
while (n != 0) {
n ^= n & (-n);
count++;
}
System.out.println(count);
}

private static void countOne2(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
System.out.println(count);
}

private static void countOne3(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>>= 1;
}
System.out.println(count);
}

  /** 此方法不正确,反例 -1 */
private static void countOne4(int n) {
int count = 0;
while (n != 0) {
if (n % 2 != 0) {
count++;
}
n /= 2;
}
System.out.println(count);
}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */