Special Bit Numbers

A number is known as a special bit number if its binary representation contains at least two consecutive 1's or set bits. For example 

7 with binary representation 111 is a special bit number. Similarly 3 (11) is also a special bit number as it contains at least two consecutive set bits or ones.

Now the problem is, You are given an array of N integers and Q queries. Each query is defined by two integers LR. You have to output the count of special bit numbers in the range L to R.

Example:

Input: n = 5, q = 3, a = [3, 5, 1, 12, 7], queries={{1,3},{2,3},{1,5}}

Output:

1 0 3

C++

#include <bits/stdc++.h>
using namespace std;
long long arr[1000010];
long long tree[2000010];

bool special(long long n)
{
    if ((n & (n >> 1)) != 0)
        return true;
    else
        return false;
}
void build(long long nodelong long startlong long end)
{
    if (start == end)
    {

        if (special(arr[start]))
            tree[node] = 1;
        else
            tree[node] = 0;
    }
    else
    {
        long long mid = (start + end) / 2;
        build(2 * nodestartmid);
        build(2 * node + 1mid + 1end);
        tree[node] = tree[2 * node] + tree[2 * node + 1];
    }
}
long long query(long long nodelong long start
long long endlong long llong long r)
{
    if (r < start || l > end)
        return 0;
    if (l <= start && r >= end)
        return tree[node];
    else
    {
        long long mid = (start + end) / 2;
        long long p1 = query(2 * nodestartmidlr);
        long long p2 = query(2 * node + 1mid + 1endlr);
        return p1 + p2;
    }
}

void specialBitNumbers(int nint q
vector<vector<int>> &queries)
{

    for (int i = 0i < qi++)
    {
        long long l = queries[i][0]r = queries[i][1];
        long long ans = query(11nlr);
        cout << ans << "\n";
    }
}
int main()
{
    long long n = 5q = 3;
    int a[] = {351127};

    for (long long i = 1i <= ni++)
        arr[i] = a[i - 1];
    vector<vector<int>> queries = {{13}, {23}, {15}};
    build(11n);
    specialBitNumbers(nqqueries);
    return 0;
}


No comments:

Post a Comment