# Encode Number in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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