Simplify binary
Pyth, 20 16 bytes
u?-GTG`u+yNsTG0z
4 bytes thanks to Jakube
Half of the code (u+yNsTG0
) is simply the base conversion code.
Test Suite
u?-GTG`u+yNsTG0z
z = input() (The string of 1s and 0s)
T = 10
u z Apply until the value stops changing, starting with z
G is the current value, a string of 0s and 1s.
?-GT If G - T, e.g., G with the digits 1 and 0 removed is not empty,
G Return G, to end the iteration.
u G0 Else, reduce over G with initial value 0.
yN Double the running total
+ sT and add the next digit, cast to an int.
` Convert to string.
The input 1
is handled by the fact that u
notices the value has stopped changing.
CJam, 24 23 bytes
q{:~{1$++}*s__,(As*-!}g
Try it online in the CJam interpreter.
How it works
q Read all input.
{ }g Do:
:~ Evaluate each character. Maps '0' -> 0 and '1' -> 1.
{ }* Fold; for each integer but the first:
1$ Copy the second-topmost integer.
++ Add all three integers on the stack.
s__ Cast to string and push two copies.
,( Calculate string length and subtract 1.
As Push the string "10".
* Repeat the string length-1 times.
- Remove its elements from the string representation
of the integer.
! Apply logical NOT.
If `!' pushed 1, repeat the loop.
Pip, 28 27 bytes
Ta=1|aRMta:$+(^a)*2**RV,#aa
Takes input as a command-line argument. We want to loop until a=1
or a
contains some character(s) besides 0's and 1's. This latter condition is tested by RM
'ing all characters in t
= 10
from a
. If there's anything left, the condition is truthy.
Inside the loop, the conversion works as follows:
a:$+(^a)*2**RV,#a
,#a range(len(a))
RV reversed
2** 2 to the power of each element
(^a)* multiplied item-wise with each digit in split(a)
$+ Sum
a: and assign back to a
Putting a
at the end auto-prints it.
A recursive solution in 28 bytes:
a<2|aRMt?a(f$+(^a)*2**RV,#a)