Number of 1 Bits(Easy)

题目: Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).--编写函数接收一个无符号整数,返回其二进制形式中包含的1的个数(也叫做汉明权重)

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

 public int hammingWeight(int n) {
    int answer = 0; // initializing answer
    for (int i = 0; i < 32; i++) { // 32 bit integers
        if(((n >> i) & 1) == 1)
            answer++;
    }
    return answer;
}

每次运行:x & (x-1),x中包含的1的个数减1,根据这一点,我们可以用下面的算法求一个数中1的位数:

 int number_of_ones(int x) {
    int total_ones = 0;
    while (x != 0) {
        x = x & (x-1);
        total_ones++;
    }
    return total_ones;
}

results matching ""

    No results matching ""