Counting Bits – Leetcode Solution

In this post, we are going to solve the 338. Counting Bits problem of Leetcode. This problem 338. Counting Bits is a Leetcode easy level problem. Let’s see the code, 338. Counting Bits – Leetcode Solution.

Problem

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1’s in the binary representation of i.

Example 1 :

Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10

Example 2 :

Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

Constraints

  • 0 <= n <= 105

Now, let’s see the code of 338. Counting Bits – Leetcode Solution.

Counting Bits – Leetcode Solution

338. Counting Bits – Solution in Java

class Solution {
    public int[] countBits(int n) {
        int[] arr = new int[n+1];
        for(int i=1;i<=n;i++){
            arr[i] = arr[(i&(i-1))]+1;
        }
        return arr;
    }
}

338. Counting Bits – Solution in C++

class Solution {
public:
    vector<int> countBits(int n) {

        vector<int> t(n+1);  
        t[0] = 0;
        
        for(int i = 1; i<=n; ++i)
            t[i] = t[i/2] + i%2;
        
        return t;
    }
};

338. Counting Bits – Solution in Python

def countBits(self, num: int) -> List[int]:
    counter = [0]
    for i in range(1, num+1):
        counter.append(counter[i >> 1] + i % 2)
    return counter

Note: This problem 338. Counting Bits is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *