LeetCode 191: Number of 1 Bits Solution
Master LeetCode problem 191 (Number of 1 Bits), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
191. Number of 1 Bits
Problem Explanation
Explanation:
To find the number of set bits in the binary representation of a positive integer n, we can use the bitwise AND operation with 1 to check the least significant bit. If the result is 1, we increment a counter. We then right shift the number by 1 bit to move to the next bit. We repeat this process until the number becomes 0.
Time complexity: O(log n) - where n is the input number
Space complexity: O(1)
Solution Code
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>>= 1;
}
return count;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 191 (Number of 1 Bits)?
This page provides optimized solutions for LeetCode problem 191 (Number of 1 Bits) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 191 (Number of 1 Bits)?
The time complexity for LeetCode 191 (Number of 1 Bits) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 191 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 191 in Java, C++, or Python.