LeetCode 338: Counting Bits Solution
Master LeetCode problem 338 (Counting 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.
338. Counting Bits
Problem Explanation
Explanation
We can solve this problem using dynamic programming. For any number i, the number of set bits in i can be determined by adding 1 to the count of set bits in i/2 if i is odd, and taking the count of set bits in i/2 if i is even. We can build the result array iteratively based on this logic.
- Time complexity: O(n)
- Space complexity: O(n)
Solution Code
class Solution {
public int[] countBits(int n) {
int[] ans = new int[n+1];
for (int i = 1; i <= n; i++) {
ans[i] = ans[i >> 1] + (i & 1);
}
return ans;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 338 (Counting Bits)?
This page provides optimized solutions for LeetCode problem 338 (Counting 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 338 (Counting Bits)?
The time complexity for LeetCode 338 (Counting Bits) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 338 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 338 in Java, C++, or Python.