Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of
0
or1
for each term:
25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1
The choice of
0
and1
is... not very binary. We shall perform the true binary expansion by expanding with powers of 2, but with a coefficient of1
or-1
instead:
25 = 1*16 + 1*8 + 1*4 - 1*2 - 1*1
Now this looks binary.
Given any positive number, it should be trivial to see that:
- Every odd number has infinitely many true binary expansions
- Every even number has no true binary expansions
Hence, for a true binary expansion to be well-defined, we require the expansion to be the least, i.e with the shortest length.
Given any positive, odd integer n
, return its true binary expansion, from the most significant digit to the least significant digit (or in reversed order).
Rules:
- As this is code-golf, you should aim to do this in the shortest byte count possible. Builtins are allowed.
- Any output that can represent and list the coefficients is acceptable: an array, a string of coefficients with separators, etc...
- Standard golfing loopholes apply.
- Your program should work for values within your language's standard integer size.
Test Cases
25 -> [1,1,1,-1,-1]
47 -> [1,1,-1,1,1,1]
1 -> [1]
3 -> [1,1]
1234567 -> [1,1,-1,-1,1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,1,1]
0
instead of-1
for the low-voltage state. The caller receiving the bits knows what they mean. (It's still a non-trivial bit-manipulation exercise, since a rotate right only works if it has 32 significant bits. e.g. a 5-bit number needs a rotate width of 5.) \$\endgroup\$111-1-1
a valid output for25
? \$\endgroup\$