Encode Number in C++


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 −

NumberEncoded 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 −

  • Create one method called bin, this will take n and k, this method will act like below
  • res := empty string
  • while n > 0
    • res := res + the digit of n mod 2
    • n := n /2
  • reverse the number res
  • while x > length of res
    • res := prepend 0 with res
  • return res
  • The actual method will be as follows −
  • if n = 0, then return empty string, if n is 1, return “0”, or when n is 2, then return “1”
  • x := log n base 2
  • if 2 ^ (x + 1) – 1 = n, then
    • ans := empty string
    • increase x by 1
    • while x is not 0, then ans := append 0 with ans, and increase x by 1
    • return ans
  • return bin(n – 2^x + 1, x)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#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;
}

Input

23
54

Output

1000
11001

Updated on: 02-May-2020

358 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements