Header Ad

HackerEarth Special Bit Numbers problem solution

In this HackerEarth Special Bit Numbers problem solution, 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 L, R. You have to output the count of special bit numbers in the range L to R.


HackerEarth Special Bit Numbers problem solution


HackerEarth Special Bit Numbers problem solution.

#include <bits/stdc++.h>

using namespace std;

int main()
{

int n, q;
cin >> n >> q;

int pre[n + 1] = {};

for(int i = 1; i <= n; i++){

int x;
cin >> x;
pre[i] = pre[i - 1];
if(x & (x << 1))
pre[i]++;

}


while(q--){

int l, r;
cin >> l >> r;

cout << pre[r] - pre[l - 1] << endl;

}

return 0;
}

Second solution

#include<bits/stdc++.h>
#define LL long long int
#define M 1000000007
#define endl "\n"
#define eps 0.00000001
#define check(a , b , c) assert(a >= b && a <= c)
LL pow(LL a,LL b,LL m){LL x=1,y=a;while(b > 0){if(b%2 == 1){x=(x*y);if(x>m) x%=m;}y = (y*y);if(y>m) y%=m;b /= 2;}return x%m;}
LL gcd(LL a,LL b){if(b==0) return a; else return gcd(b,a%b);}
LL gen(LL start,LL end){LL diff = end-start;LL temp = rand()%start;return temp+diff;}
using namespace std;
int a[100001];
int main()
{
ios_base::sync_with_stdio(0);
int n , q;
cin >> n >> q;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
int pre = 0 , cur = 0;
while(a[i])
{
cur = a[i] % 2;
if(pre == 1 && cur == 1)
{
a[i] = 1;
break;
}
pre = cur;
a[i] /= 2;
}
a[i] = a[i - 1] + a[i];
}
while(q--)
{
int l , r;
cin >> l >> r;
cout << a[r] - a[l - 1] << endl;
}
}

Post a Comment

0 Comments