Loading

计算二进制数中1的个数

输入一个整数,计算出该整数对应二进制数中 1 的个数(整数包含正整数和负整数)

public static void main(String[] args) {
    System.out.println(solution03(-4));	// 30
    System.out.println(Integer.toBinaryString(-4));// 11111111111111111111111111111100
}

/**
 * 该算法 对整数对应的二进制数 进行运算
 * 运算方法为 n = n & (n - 1 )
 * 即 n & (n - 1 ) = 0110 & 0101 = 0100 赋值给 n, COUNT++
 * 0100 & 0011 = 0000 赋值给 n ,COUNT++
 * n = 0 时,结束运算
 */
public static int solution03(int num) {
    int count = 0;
    while (num != 0) {
        num = (num - 1) & num;
        count++;
    }
    return count;
}
posted @ 2020-08-13 10:54  codeduck  阅读(253)  评论(0编辑  收藏  举报