返回

[Leetcode]191. Number of 1 Bits(C++)

题目描述

题目链接:191. Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

例子

例子 1

Input:n = 00000000000000000000000000001011 Output:3 Explanation:The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

例子 2

Input:n = 00000000000000000000000010000000 Output:1

例子 3

Input:n = 11111111111111111111111111111101 Output:31 Explanation:The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Follow Up

  • If this function is called many times, how would you optimize it?

Note

  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

Constraints

  • The input must be a binary string of length 32.

解题思路

简单的位操作即可,将数与 1 相与获取最低位的值并且不断将数字右移直至数字为 0 为止,代码如下:

#include <cstdint>

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        while (n != 0) {
            count += (n & 0x1);
            n >>= 1;
        }
        return count;
    }
};
  • 时间复杂度: O(1)
  • 空间复杂度: O(1)

GitHub 代码同步地址: 191.NumberOf1Bits.cpp

其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions

Built with Hugo
Theme Stack designed by Jimmy