Cars in the Lane

You are given IDs of different uni-directional highways in the ByteLand. The highways are quite mysterious. If you convert their IDs to a binary number then it means that the bit position where the value is 

0, those lanes are closed or else the lanes are open. Now for each highway, you need to count in how many ways the open lanes of the highway can be occupied.

Note: If none of the lanes are occupied then also it is counted as a way.

Example:

Input:  n = 4
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;

long long setBits(long long n)
{
    long long res = 0;
    while (n)
    {
        res++;
        n = n & (n - 1);
    }
    return res;
}
int main()
{
    long long n = 4;

    long long ans = setBits(n);
    if (ans == 1)
        cout << 2 << "\n";
    else
    {
        cout << pow(2ans<< "\n";
    }

    return 0;
}


No comments:

Post a Comment