Represent a Number as Sum of Minimum Possible Pseudo-Binary Numbers in C++

C++Server Side ProgrammingProgramming

This tutorial will discuss the representation of a number as a sum of minimum pseudo-binary numbers. Pseudo-binary numbers are the numbers that consist of only binary digits, i.e., 0 and 1. Examples of pseudo-binary numbers are 00, 11, 10, 100, 111, 1011, etc.

Below are some examples of numbers represented as the sum of pseudo-binary numbers.

Input : 23
Output : 11 + 11 + 1
Explanation : 23 = 11 + 11 + 1, sum of pseudo-binary numbers(11, 11, 1) is 23.

Input : 50
Output : 10 + 10 + 10 + 10 + 10

Approach to Find the Solution

Below is one of the best approaches to find minimum pseudo-binary numbers to represent N.

  • Take a number X and update its digits to 1 or 0 according to the digits of the number N.

  • Check digit at each place of N,

    • If it is 0, then update that place of X to 0.

    • If it is not zero, update that place of X to 1.

    • Let’s say N = 32, then X will be 11

  • Then X will be one pseudo-binary number.

  • Now decrement N by X and repeat step1 until N becomes zero.

Example

C++ Code for the Above Approach

#include<iostream>
using namespace std;
int main(){
   int N = 51;
   // find a pseudo-binary number until N becomes 0.
   cout << "pseudo-binary representation of " << N << " is: ";
   while (N > 0){                
      // finding X which contains 0's and 1's according to N.
      int temp = N;
      int X = 0, bit = 1;
      // checking each place of N for zero or non-zero.
      while (temp!=0){
      int last_dig = temp % 10;
      temp = temp / 10;
      if (last_dig != 0)
         X += bit;
         bit *= 10;
      }
      // printing one pseudo-binary number.
      cout << X << " ";
      // Updating N by subtracting with X.
      N = N - X;
       
   }
   return 0;
}

Output

pseudo-binary representation of 51 is: 11 10 10 10 10

Understanding the Code

  • An outer while loop for taking N and picking digits on every place to find X.

  • We are updating the value of the temp variable with N and Inner loop for checking each place of temp variable and updating that place of variable X.

  • Printing value of X because that is one pseudo-binary number.

  • We update N by subtracting with X and going to the outer loop again until N becomes 0.

Conclusion

In this tutorial, we have discussed how we can represent a number as a sum of minimum possible pseudo-binary numbers. We discussed the approach to find all the pseudo-binary numbers. We also discussed the C++ code for the same, which we can write in any other programming language like C, Java, Python, etc. We hope you find this tutorial helpful.

raja
Published on 26-Nov-2021 06:46:41

Advertisements