Very Cool Number | Coolness of Binary Equivalent | Solution

Problem: For number X, let it’s Coolness is defined as the number of “101“s occurring in it’s Binary representation.

For example the number 21 has a coolness of 2 since it’s binary representation is 10101 and the string”101” occurs twice in this representation.

A number is Very Cool if it’s coolness is greater than or equal to K. Please output the very cool integers between 1 and R.

Input format: The first line contains a single integer denotes the number of testcases T. The next T lines contains two space separated integers R and K.

(NOTE: The actual problem didn’t have the number of testcases as input. But for your better convenience we have worked with testcases. Omit the testcase input line to get the actual format.)

Output format: Print the single integer representing the number of Very Cool integers between 1 and R.

Constraints:
1<=R<=105
1<=K<=100

Sample Input:

2
102 1
21 2

Sample Output:

48
1

Solution: We strongly recommend you to try the problem first before moving to the solution.

C++ (STL)

/* C++ code for Very Cool number */
/* www.codewindow.in */

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

// Function for converting decimal to binary and return as string 
string dec_to_binary(int n) {
    string s;
    for(int i=15; i>=0; --i) {  // Supposing sizeof integer as 16 bits
        int temp=n>>i;
        if(temp & 1)
            s+='1';
        else
            s+='0';
    }
    return s;
}

// Solution Function
void solve() {
    int n, k, r, ans=0, cool;
    cin >> r >> k;
    for(int num=1; num<=r; ++num) {
        cool=0;
        string s=dec_to_binary(num);
        for(int i=0; i<s.length(); ++i) {
            string temp=s.substr(i, 3);  // Substring of size 3 starting from i
            if(temp=="101")
                ++cool;
        }
        if(cool>=k)  // If (coolness>=k) then count it 
            ++ans;
    }
    cout << ans << "\n";
}

// Driver code
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    int t=1;
    cin >> t;   // Input the testcases
     while(t--)
        solve();
        
    return 0;
}

Input:

2
102 1
21 2

Output:

48
1

Follow Us

You Missed


Leave a Comment

Your email address will not be published. Required fields are marked *