← Back to challenges

Sums of Powers of Two

JavaScriptHardnumbersalgorithmsmath

Instructions

Every number can be expressed as the sum between unique powers of two. For example, the number 21 can be expressed as 1 + 4 + 16, which can also be written as 2^0 + 2^2 + 2^4.

Create a function that returns a sorted list of powers of two, which add together to make n.

Examples

sumsPowersTwo(21) ➞ [1, 4, 16]

sumsPowersTwo(8) ➞ [8]

sumsPowersTwo(63) ➞ [1, 2, 4, 8, 16, 32]

Notes

Tests will only include positive whole numbers.

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.