leetcode系列191-位1的个数

    技术2025-08-29  10

    【题目概要】

    191. Number of 1 Bits Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight). Example 1: Input: 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

    【思路分析】

    计算位数上1的个数,直接用&运算即可,循环中用while比用for效率更好,较少n等于0后的不必要的运算

    【代码示例】

    int hammingWeight(uint32_t n) { int count = 0; while(n) { if(n & 0x01) count++; n = n >> 1; } return count; }
    Processed: 0.013, SQL: 9