Likou 191. The number of bit 1 (bit operation)

191. Number of Bit 1

Write a function, the input is an unsigned integer (in the form of a binary string), and returns the number of digits in the binary expression whose digits are '1' (also known as Hamming weight).

prompt:

Please note that in some languages ​​(such as Java), there is no unsigned integer type. In this case, both input and output will be designated as signed integer types, and should not affect your implementation, because the internal binary representation is the same regardless of whether the integer is signed or unsigned.
In Java, the compiler uses two's complement notation to represent signed integers. Therefore, in example 3 above, the input represents a signed integer -3.

示例 1:

输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:

输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:

输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
 

提示:

输入必须是长度为 32 的 二进制串 。

answer:

According to the definition of decimal binary, we only need to continuously divide a decimal number by 2, and each time we will get a remainder 0 or 1, and then until the decimal number is 0, all remainders are arranged from back to front. At this time The result is a binary number.
And what we want is the number of 1, so we only need to add the remainder each time to get the number of 1. This is because the remainder being 0 does not affect the calculation of 1.

Code:

int hammingWeight(uint32_t n) {
    
    
    int m = 0;
    while(n)
    {
    
    
        m += n%2;
        n/=2;//也可以由位运算写成n=n>>1
    }
    return m;
}

Method two: bit operation

We can directly use bit operations for calculations.
Based on the concept of bitwise AND, we can perform bitwise AND for n to 1 each time. In this way, if the last bit of n is 1, the result will also be 1, and it will be found when the last bit of n is 0. Will not get 1. Then divide n by 2 each time, that is, shift 1 bit to the right.
That is, it is directly judged whether the lowest bit of the binary is 1 each time.

//直接判断二进制最低位的数是不是1
int hammingWeight(uint32_t n) {
    
    
    int m = 0;
    while(n)
    {
    
    
        m+=n&1;
        n>>1;
    }
    return m;
}

Guess you like

Origin blog.csdn.net/xiangguang_fight/article/details/115108271