Leetcode 191 Number of 1 bits

106 阅读1分钟

这篇是bits Manipulation基本操作的入门学习

Leetcode 191

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

n >> 1 n 向右移一位

n & 1 n最后一位是1(同样常用于判断奇、偶,偶数末尾为0,奇数末尾为1)

7/16/2024

我自己写的新代码解, 我个人觉得更好 嘿嘿

class Solution {
public:
    int hammingWeight(int n) {
        int count = 0;
        while(n){
            if(n & 1) count++;
            n = n >> 1;
        }
        return count;
    }
};

Extra Exercise:

78. Subsets

这道题归为backtracking 回溯类内。可以用bit 思想去做