191. Number of 1 Bits LeetCode Solution

In this guide, you will get 191. Number of 1 Bits LeetCode Solution with the best time and space complexity. The solution to Number of Bits problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Number of Bits solution in C++
  4. Number of Bits solution in Java
  5. Number of Bits solution in Python
  6. Additional Resources
191. Number of 1 Bits LeetCode Solution image

Problem Statement of Number of Bits

Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).

Example 1:

Input: n = 11
Output: 3
Explanation:
The input binary string 1011 has a total of three set bits.

Example 2:

Input: n = 128
Output: 1
Explanation:
The input binary string 10000000 has a total of one set bit.

Example 3:

Input: n = 2147483645
Output: 30
Explanation:
The input binary string 1111111111111111111111111111101 has a total of thirty set bits.

Constraints:

1 <= n <= 231 – 1

Follow up: If this function is called many times, how would you optimize it?

Complexity Analysis

  • Time Complexity: O(32) = O(1)
  • Space Complexity: O(1)

191. Number of 1 Bits LeetCode Solution in C++

class Solution {
 public:
  int hammingWeight(uint32_t n) {
    int ans = 0;

    for (int i = 0; i < 32; ++i)
      if ((n >> i) & 1)
        ++ans;

    return ans;
  }
};
/* code provided by PROGIEZ */

191. Number of 1 Bits LeetCode Solution in Java

class Solution {
  // You need to treat n as an unsigned value
  public int hammingWeight(int n) {
    int ans = 0;

    for (int i = 0; i < 32; ++i)
      if (((n >> i) & 1) == 1)
        ++ans;

    return ans;
  }
}
// code provided by PROGIEZ

191. Number of 1 Bits LeetCode Solution in Python

class Solution:
  def hammingWeight(self, n: int) -> int:
    ans = 0

    for i in range(32):
      if (n >> i) & 1:
        ans += 1

    return ans
# code by PROGIEZ

Additional Resources

See also  787. Cheapest Flights Within K Stops LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.