The Lucas Virgili's answer explains well the rationale behind the question (which certainly is even about binary representation ), but I would like to give you a slightly more general answer:
When you get any number in the abstract and represent that number in a base , you are just breaking it down into a series of smaller numbers. For example:
44 = 10*4 + 1*4 (base 10: 44)
= 16*2 + 1*12 (base 16: 2C)
= 32*1 + 16*0 + 8*1 + 4*1 + 2*0 + 1*0 (base 2: 101100)
And so on. In the case of binary numbers, there are only two possibilities: either the component is present or not:
1, 2, 4, 8, 16, 32,...
In the case of numbers in decimal, for example, each component can occur from 0
to 9
times:
1,1,1,1,1,1,1,1,1, 10,10,10,10,10,10,10,10,10, 100,100,100,100,100,100,100,100,100, 1000...
And so on. In order to "assemble" the number 44
, we take 4 units (i.e. from the 9% available% coefficients we get 4) and 4 tens (from the 9% available coefficients we get 4). No hundred, thousand, etc.
This reasoning is true even for "crazy" bases, such as "represent an amount in Reais using as few notes as possible":
1c,1c,1c,1c, 5c, 10c,10c, 25c, 50c, R$1, R$2,R$2, R$5, R$10,R$10, R$20, R$50, R$100...
R$44 = R$20 + R$10 + R$10 + R$2 + R$2
Reverse Method
The most efficient way to solve this problem (to represent a given number of components) is to start with the "largest of them" (or, if the sequence is infinite, the largest of them is less than or equal to the number ) and scroll through the list to the beginning - subtracting the values found until the number reaches zero:
entrada = 44
lista = [1,2,4,8,16,32,64,128]
maior = x in lista if x <= entrada
for y from maior to 0:
if y <= entrada:
incluir y na saída
entrada -= y
Except for the binary case (where bit testing is simpler and more efficient - since the computer "helps" the task with binary operators for it), this would be the best way to do an arbitrary input [ ordered in ascending order, of course].
Direct method
Remember the primary when you learned how to make sums using QVL ? The same principle can be used, but using an arbitrary base instead of 10:
- As long as the value to be reached is greater than zero:
- Take the lowest value from the list (unit), and add it to the output - decrementing the input
- If the lowest value in the list is not available (ie all units have been used), remove N values from the output and change them to a larger value (ten) - so that N units + 1 unit is equal to ten.
- Repeat recursively for larger quantities (tens / hundreds, hundreds / thousands, etc.).
I quoted this method out of curiosity only, since needless to say it is too inefficient (you would be "counting" from 1 to 44 - 1
complexity), I leave the implementation in code as exercise for the reader ...: P