Counting Bits LeetCode

 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

 


Follow up:


It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?

Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?



Approach 1 : Using Builtin function

class Solution {
    public int[] countBits(int n) {
        // Create an array to store the result for each number from 0 to n
        int[] arr = new int[n + 1];

        // Loop through every number from 0 to n
        for (int i = 0; i <= n; i++) {
            // Count the number of set bits (1s) in binary of i using built-in function
            int count = Integer.bitCount(i);

            // Store the count at the ith index in the result array
            arr[i] = count;

            // Reset count (optional here since count is re-initialized every time)
            count = 0;
        }

        // Return the array of bit counts
        return arr;
    }
}



Approach 2: Using Left Shift in the Outer Loop


class Solution {
    public int[] countBits(int n) {
        int[] arr = new int[n + 1];

        // Use left shift to generate numbers from 0 to n (not necessary, but as per request)
        for (int i = 0; i <= n; i++) {
            arr[i] = countSetBits(i); // Count bits without built-in function
        }

        return arr;
    }

    // Count set bits manually without using bitCount
    public int countSetBits(int num) {
        int count = 0;

        // We use a mask that starts at 1 and we left shift it
        // So we check each bit position from right to left
        for (int i = 0; i < 32; i++) {
            if ((num & (1 << i)) != 0) {
                count++;
            }
        }

        return count;
    }
}



๐Ÿ” Explanation:

1 << i (Left Shift)

  • 1 << 0 → 0001 → Checks the 1st bit

  • 1 << 1 → 0010 → Checks the 2nd bit

  • 1 << 2 → 0100 → Checks the 3rd bit

  • And so on…

We use this to create a bitmask and check every bit of the number using:

if ((num & (1 << i)) != 0)

If the result is not zero, that bit is 1.

Loop i = 0:  1 << 0 = 0001  → 0101 & 0001 = 0001 → count++

Loop i = 1:  1 << 1 = 0010  → 0101 & 0010 = 0000 → skip

Loop i = 2:  1 << 2 = 0100  → 0101 & 0100 = 0100 → count++

 Set Bits = 2
๐Ÿงพ Final Output Example (n = 5):
Input: 5
Output: [0, 1, 1, 2, 1, 2]


Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence