Problem with numbers
I am given a number N, and i must add some numbers from the array V so that they wil be equal. V is consisting of numbers that are all powers of 3:
N = 17
S = 0
V = 1 3 9 27 81 ..
I should add numbers from V to N and S in order to make them equal. The solution to the example above is :
17 + 1 + 9 = 27
, 27, 1 and 9 are taken from V, a number from V can be taken only once, and when taken it's removed from V.
I tried sorting V and then adding the biggest numbers from V to S until S has reached N, but it fails on some tests when it's like:
N = 7
S = 0
V = 1 3 9 27
So the solution will be:
7 + 3 = 9 + 1
In examples like this i need to add numbers both to N and S, and also select them so they become equal. A开发者_如何转开发ny idea of solving this ? Thanks.
Write N in base 3: 17 = 2*1 + 2*3 + 1*9
Find the first power of 3 with coefficient 2, in this case 1.
Add this power of 3: 17 + 1
Repeat until all coefficients are 0 or 1.
17 = 2*1 + 2*3 + 1*9
17 + 1 = 2*9
17 + 1 + 9 = 27
7 = 1*1 + 2*3
7 + 3 = 1*1 + 1*9
精彩评论