Reverse and square
Mathematica, 42 21 bytes
Thanks to alephalpha for halving the score.
#~IntegerReverse~2^2&
The actual reason I did this in Mathematica was because I wanted to look at a plot... it sure looks funny:
Japt, 29 28 11 7 bytes
(You can save the program as a 7-byte IEC_8859-1-encoded file, then upload it to the interpreter.)
Japt is shortened JavaScript made by ETHproductions.
¢w n2 ²
Try it online!
Explanation:
¢
is shortcut toUs2
, which compiles toU.s(2)
.U
is input (implicit),.s(2)
called by a number, invokes.toString(2)
(converts to binary, parses as string).w
compiles to.w()
, which reverses the string (.split('').reverse().join('')
).n2
works asparseInt(<number>,2)
, i.e. converts binary to decimal.²
invokesMath.pow(<number>,2)
, i.e. squares the number.
Minkolang 0.14, 43 bytes
Thanks to Mego for inspiring this.
n1{d1`,2$3*&$z2zd2%-2l$Md1%-;z2%*z2:{+}2;N.
Test the code here and check all test cases here.
Explanation
This uses this recurrence relation:
a(0) = 0
a(1) = 1
a(2n) = a(n)
a(2n+1) = a(n) + 2^(floor(log_2(n))+1)
If n
is the input, then a(n)
is the resulting number after its binary sequence has been flipped. 0 and 1 are obvious. For a(2n) = a(n)
, consider that x0
(where x
is any sequence of binary digits) flipped is 0x
, which is the same as x
. For a(2n+1)
, the reasoning is a bit more complicated. x1
flipped is 1x
, which is equal to x + 2^k
for some k
. This k
is one more than the number of digits in x
, which is floor(log_2(n))+1
. The full formula follows, except that it's modified a bit. This is what I actually code:
a(0) = 0
a(1) = 1
a(n) = a(n//2) + (n%2) * 2^(floor(log_2(n - n%2)))
As Mego and I worked out in chat, floor(n/2) = (n - n%2)/2
. Thus, log_2(floor(n/2))+1 = log_2(n - n%2)
. Furthermore, multiplying by (n%2)
collapses both the odd and even parts into one expression.
Finally, without any further ado, here's the code, explained.
n Take number from input
1{ Start recursion that takes only one element
d1`, 1 if top of stack 0 or 1, 0 otherwise
2$3* 26
& Jump if top of stack is not zero
$z Store top of stack in register (z)
zd2%- n - n%2
2l$M log_2(n - n%2)
d1%- floor(log_2(n - n%2))
2 ; 2^floor(log_2(n - n%2))
z2% n%2
* Multiply
z2: n//2
{ Recurse
+ Add
} Return
2;N. Square it, output as number, and stop.