Play with Bits!

You have recently learned about the conversion of decimal numbers into binary form. Now you are given an array of size N. You need to convert each of the numbers to its binary form, switch the bits (if it's 0 then switch it to 1 and vice versa), and join each of these converted binary numbers to form a big string.

Now you need to print the count of the number of 1s in the given string. 

Example:

Input:  n= 3, a = [4,2,3]
Output: 3

Approach

C++

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

long long playBits(long long n)
{
    long long res = 0;
    long long x = log2(n) + 1;
    while (n)
    {
        res++;
        n = n & (n - 1);
    }

    return x - res;
}
int main()
{
    long long n = 3;
    long long a[n] = {423};

    long long ans = 0;
    for (long long i = 0i < ni++)
        ans += playBits(a[i]);
    cout << ans << "\n";
    return 0;
}


No comments:

Post a Comment