
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 −
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 −
- 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
#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
- Related Articles
- Understanding base64 encode in MySQL?
- Encode and Decode Strings in C++
- Encode string array values in Numpy
- How to encode the string in android?
- How to encode a string in JavaScript?
- Encode String with Shortest Length in C++
- Arduino – base64 encode and decode
- How can I encode a URL in Android?
- How to encode and decode URl in typescript?
- How to URL encode a string (NSString) in iPhone?
- How can we encode a JSON object in Java?
- What is the difference between encode/decode in Python?
- Encode N-ary Tree to Binary Tree in C++
- How to encode and decode a URL in JavaScript?
- Encode and decode uuencode files using Python

Advertisements