Binary numbers

You are given a set of binary elements. You have to eliminate the binary numbers that contain 

11 as a substring. The resultant sequence will be 1, 10, 100, 101, 1000, and so on.

You are required to generate the code to determine the Kth value of the new sequence.

Example:

Input:  n = 3
Output: 100

Approach

C++

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

string binaryNumbers(int n)
{
    vector<inta(40);
    a[0] = 1;
    a[1] = 2;
    for (int i = 2i < 40i++)
        a[i] = a[i - 1] + a[i - 2];
    string s = "";

    int f = 0;
    for (int i = 39i >= 0i--)
    {
        if (a[i] <= n)
        {
            s += '1';
            f = 1;
            n = n - a[i];
            continue;
        }
        if (f)
            s += '0';
    }
    return s;
}
int main()
{
    int n = 3;

    cout << binaryNumbers(n<< "\n";

    return 0;
}


No comments:

Post a Comment