Find the number of 1 in a binary sequence

When writing leetcode, I have encountered several problems that need to quickly find the number of 1 in a binary sequence, so here is a summary of several methods.

Links to typical topics

Bitwise judgment

This is the simplest and most intuitive way to determine whether each digit of an integer is 1 in turn.

Judge the first bit: n & 1
Judge the second bit: n & (1 << 1)
Judge the nth bit: n & (1<<(n-1))

class Solution {
    
    
public:
    int hammingWeight(uint32_t n) {
    
    
        int ret = 0;
        for (int i = 0; i < 32; i ++) {
    
    
            if (n & (1 << i)) {
    
    
                ret ++;
            }
        }
        return ret;
    }
};

Shortcut method: N & (N-1)​

Using this method is based on the fact:

一个数 n 与一个比它小 1 的数(n−1)进行与运算(&)之后,得到的结果会消除 n 中最低位的 1

For example:
7&6
00111 & 00110 =00110

It can be seen that the result of n&(n−1) is the value after replacing the lowest bit of n with 0.

This algorithm is used to eliminate 1 each time, and the counter is +1 each time until n is 0.

class Solution {
    
    
public:
    int hammingWeight(uint32_t n) {
    
    
        int res = 0;
		while (n) {
    
    
			n = n&(n - 1);
			res++;
		}
		return res;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45605341/article/details/108033301