Subject:
Computer ScienceAuthor:
raison7laaCreated:
1 year agoAnswer:
Approach:Explanation:
#include<bits/stdc++.h>
using namespace std;
// Function to return the
// pre-calculate array such
// that arr[i] stores the count of
// valid numbers in the range [0, i]
string DecimalToBinaryString(int a)
{
string binary = "";
int mask = 1;
for (int i = 0; i < 31; i++)
{
if(mask&a)
binary = "1" + binary;
else
binary = "0" + binary;
mask <<= 1;
}
return binary;
}
vector<int> preCalculate(int max,
string pattern)
{
vector<int> arr(max + 1, 0);
// If 0 is a valid number
if (pattern == "0")
arr[0] = 1;
else
arr[0] = 0;
// For every element i
for (int i = 1; i <= max; i++)
{
// If i is avalid number
if (DecimalToBinaryString(i).find(pattern) !=
std::string :: npos)
{
arr[i] = 1 + arr[i - 1];
}
else
{
arr[i] = arr[i - 1];
}
}
return arr;
}
// Function to perform the queries
void performQueries(vector<vector<int> > queries,
int q, string pattern)
{
// Maximum value for the
// end of any range
int ma = INT_MIN;
for (int i = 0; i < q; i++)
ma = max(ma, queries[i][1]);
// res[i] stores the count of valid
// integers from the range [0, i]
vector<int> res = preCalculate(ma,
pattern);
for (int i = 0; i < q; i++)
{
int l = queries[i][0];
int r = queries[i][1];
if (l == 0)
cout << (res[r]) << endl;
else
cout << (res[r] -
res[l - 1]) << endl;
}
}
// Driver code
int main()
{
vector<vector<int>> queries = {{2, 10},
{8, 120}};
int q = queries.size();
string pattern = "101";
performQueries(queries, q, pattern);
}
// This code is contributed by grand_master
Author:
cabrera73
Rate an answer:
6