Number of 1 Bits - Complete Solution Guide
Number of 1 Bits is LeetCode problem 191, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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
Detailed Explanation
The problem asks you to count the number of bits that are set to 1 in the binary representation of a given positive integer. The input is a positive integer `n`, and the output is the number of 1s in its binary representation. For example, the binary representation of 11 is 1011, which has three 1s. The constraints specify that the input integer `n` will always be between 1 and 2<sup>31</sup> - 1 (inclusive), meaning it fits within a 32-bit signed integer.
Solution Approach
The provided code uses a bit manipulation technique to efficiently count the set bits. It iteratively clears the least significant set bit in the number `n` and increments a counter. This process repeats until all set bits are cleared, and the counter then holds the total number of set bits.
Step-by-Step Algorithm
- Step 1: Initialize a counter `count` to 0.
- Step 2: Enter a `while` loop that continues as long as `n` is not 0.
- Step 3: Inside the loop, perform the bit manipulation `n &= (n - 1)`. This operation clears the least significant set bit in `n`.
- Step 4: Increment the `count` by 1.
- Step 5: Repeat steps 3 and 4 until `n` becomes 0.
- Step 6: Return the final value of `count`.
Key Insights
- Insight 1: Understanding binary representation is crucial. The problem requires you to manipulate the bits directly.
- Insight 2: The clever bit manipulation trick `n &= (n - 1)` efficiently clears the least significant set bit. This is the core of the optimized solution.
- Insight 3: The loop continues until `n` becomes 0, meaning all set bits have been cleared. The count of iterations represents the total number of set bits.
Complexity Analysis
Time Complexity: O(log n)
Space Complexity: O(1)
Topics
This problem involves: Divide and Conquer, Bit Manipulation.
Companies
Asked at: AMD, Box, Cisco, Qualcomm, Verkada.