Suppose we have a non-negative integer n, and we have to find the encoded form of it. The encoding strategy will be as follows −
Number | Encoded number |
---|---|
0 | “” |
1 | “0” |
2 | “1” |
3 | ”00” |
4 | ”01” |
5 | ”10” |
6 | ”11” |
7 | ”000” |
So if the number is 23, then result will be 1000, if the number is 54, then it will be 10111
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: string bin(int n, int x){ string result = ""; while(n>0){ result += (n%2) + '0'; n/=2; } reverse(result.begin(), result.end()); while(x>result.size())result = '0' + result; return result; } string encode(int n) { if(n == 0)return ""; if(n == 1)return "0"; if(n==2) return "1"; int x = log2(n); if(((1<<(x+1)) - 1) == n){ string ans = ""; x++; while(x--)ans+="0"; return ans; } return bin(n - (1<<x) + 1, x); } }; main(){ Solution ob; cout << (ob.encode(23)) << endl; cout << (ob.encode(56)) << endl; }
23 54
1000 11001