Learner Level

Implement the subsetsCountByBitmask method that returns how many subsets can be formed using bitmasking.

The input is an integer n, representing the number of elements in a set.

Your task is to return how many subsets can be formed from these n elements. A subset may include no elements, some elements, or all elements.

For example, when n = 4, each element has two choices: included or not included. Therefore, the total number of subsets is 2^4 = 16.

Example 1

Input
n (int) = 4
Returns (int) 16

Example 2

Input
n (int) = 0
Returns (int) 1

Example 3

Input
n (int) = 3
Returns (int) 8

Every element has two independent choices: either it is included in a subset or it is not included.

Because there are n elements and each has 2 choices, the total number of subsets is 2^n. This is the same idea used by bitmasking, where every bit represents whether one element is selected.

Calculate 2 multiplied by itself n times and return the result.

Pseudocode:

function subsetsCountByBitmask(n):
    count = 1
    for i from 1 to n:
        count = count * 2
    return count
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.