This tutorial will discuss representing a number as the smallest sum of pseudo-binary numbers. A pseudo-binary number is a number composed of the binary digits 0 and 1. Examples of pseudo-binary numbers are 00, 11, 10, 100, 111, 1011, etc.
Here are some examples of numbers represented as sums 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
The following is one of the best ways to find the smallest pseudo-binary number that represents N.
Take a number X and update the number of digits in X to 1 or 0 according to each digit of the number N.
Check each digit of N:
If it is 0, set that bit of X to 0.
If it is not 0, set the bit of X to 1.
Assuming N = 32, X will become 11.
# Then X will become a pseudo-binary number.
Now subtract X from N and repeat step 1 until N becomes zero.
C code for the above method
#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; }
pseudo-binary representation of 51 is: 11 10 10 10 10
An outer while loop is used to get N and select the number at each position to find X.
We do this by updating the value of N into the temp variable and using an inner loop to check each position of the temp variable and update that position of the variable X.
Print the value of X because it is a pseudo-binary number.
We update N by subtracting X from N and entering the outer loop again until N becomes 0.
In this tutorial, we discussed how to represent a number as the smallest possible sum of pseudo-binary numbers. We discussed ways to find all pseudo-binary numbers. We also discussed that the same C code we can write in other programming languages like C, Java, Python, etc. Hope you find this tutorial helpful.
The above is the detailed content of In C++, represent a number as the smallest possible sum of pseudo-binary numbers. For more information, please follow other related articles on the PHP Chinese website!