31
3
The Challenge
Given an integer input x
where 1 <= x <= 255
, return the results of powers of two that when summed give x
.
Examples
Given the input:
86
Your program should output:
64 16 4 2
Input:
240
Output:
128 64 32 16
Input:
1
Output:
1
Input:
64
Output:
64
The output may contain zeros if the certain power of two is not present in the sum.
For example, input 65
may output 0 64 0 0 0 0 0 1
.
Scoring
This is code-golf, so the shortest answer in each language wins.
5Does the list have to be sorted highest to lowest? – Adám – 2019-01-28T20:56:31.180
2May we output some redundant zeros? – Jonathan Allan – 2019-01-28T20:58:32.633
@Adám going to say yes this time. I want the output to be somewhat similar to the binary representation of the number. ie 65 = 0 + 2^6 +0 +0 +0 +0 + 0 +2^0 – SpookyGengar – 2019-01-28T21:27:05.393
@JonathanAllan yes only if the zeros are present in the list in the same way that certain powers of two may not be present in the sum. For example,
65
may output0 64 0 0 0 0 0 1
since those powers of two are not present in the sum. – SpookyGengar – 2019-01-28T21:28:46.0904RE: "sorted highest to lowest" why add a restriction that was not part of the challenge and invalidates most existing answers? (Also what about little-endian?!) + it invalidates my Python answer since sets do not have any order. – Jonathan Allan – 2019-01-28T21:38:44.927
@JonathanAllan it was always part of the problem based on the output I provided, but I added that restriction explicitly after your question as I realized some may have been confused. – SpookyGengar – 2019-01-28T22:18:43.200
1As it was written it said "Given an integer input
x
where1 <= x <= 255
, return the results of powers of two that when summed givex
.". Note that it is a common misconception that test cases are to help define a challenge. – Jonathan Allan – 2019-01-28T22:23:25.5675@JonathanAllan I've removed the restriction. I'll keep that in mind next time I post another question - I'm still fairly new to this. :) – SpookyGengar – 2019-01-28T22:28:56.827
6I think you might want to state that any power of two may only be used once. Otherwise somebody could output "1 1 1" for the input 3. – Black Owl Kai – 2019-01-29T10:58:56.023
Can the output be separated by newlines instead of spaces? – Reinstate Monica -- notmaynard – 2019-01-29T23:48:27.330
@SpookyGengar: you should probably say explicitly in the question that the output can be in any order. I assumed from the test-case valid outputs that it had to be MSB to LSB, and only saw your comment while checking if an answer that isolated the lowest bit with
n&-n
was legal. – Peter Cordes – 2019-01-30T04:49:42.747Is a leading zero in the output okay? i.e.
86
→[0, 64, 16, 4, 2]
– Oliver – 2019-01-30T20:17:53.030