33
\$\begingroup\$

So you are given a POSITIVE base 10 (decimal) number. Your job is to reverse the binary digits and return that base 10 number.

Examples:

1 => 1 (1 => 1)
2 => 1 (10 => 01)
3 => 3 (11 => 11)
4 => 1 (100 => 001)
5 => 5 (101 => 101)
6 => 3 (110 => 011)
7 => 7 (111 => 111)
8 => 1 (1000 => 0001)
9 => 9 (1001 => 1001)
10 => 5 (1010 => 0101)

This is a challenge, so the solution that uses the least bytes wins.

This is A030101 in the OEIS.

\$\endgroup\$
  • 2
    \$\begingroup\$ Does "reverse the bits" mean reverse its binary digits? Sometimes it can also mean invert every bit. \$\endgroup\$ – ETHproductions Jan 4 '17 at 18:03
  • \$\begingroup\$ Yes. Sorry for being unclear. \$\endgroup\$ – juniorRubyist Jan 4 '17 at 18:04
  • \$\begingroup\$ This and this are veeeeery similar. \$\endgroup\$ – Geobits Jan 4 '17 at 18:10
  • \$\begingroup\$ OEIS A030101. \$\endgroup\$ – orlp Jan 4 '17 at 18:12
  • 1
    \$\begingroup\$ "base 10" Any particular reason why? \$\endgroup\$ – CalculatorFeline Jun 21 '17 at 1:00

46 Answers 46

0
\$\begingroup\$

Java 7, 94 89 bytes

Golfed:

int x(int n){return Long.parseLong(new StringBuffer(Long.toString(n,2)).reverse()+"",2)};

Ungolfed:

int x(int n)
{
    return Integer.parseInt(new StringBuffer(Integer.toString(n, 2)).reverse() + "", 2);
}

5 bytes saved thanks to @corvus_192

\$\endgroup\$
  • 1
    \$\begingroup\$ You can use Long.parseLong and Long.toString to save a few bytes. \$\endgroup\$ – corvus_192 Jan 5 '17 at 20:16
0
\$\begingroup\$

Pari/GP , 28 byte

The value to be "reversed" is expected in variable a; i.e. do a=37 first. Then execute the cmd. Because Pari/GP is interpreting you do not need to add an extra print(b) because referencing a variable or a result just prints it to the console:

  b=a%2;while(a\=2,b+=b+a%2);b

Example:

  a=37
  b=a%2;while(a\=2,b+=b+a%2);b
  \\ printed result is: 41                  

Try it online!

\$\endgroup\$
0
\$\begingroup\$

SmileBASIC, 41 bytes

INPUT N
WHILE N:T=T+T+N MOD 2N=N>>1WEND?T

Basically a port of the C/Java versions.

\$\endgroup\$
0
\$\begingroup\$

8th, 41 29 bytes

2 base drop >s rev >n decimal

Usage

ok> 37 2 base drop >s rev >n decimal .
41

Test case

: f 2 base drop >s s:rev >n decimal ; 
( dup . " => " . f . cr ) 1 10 loop

1 => 1
2 => 1
3 => 3
4 => 1
5 => 5
6 => 3
7 => 7
8 => 1
9 => 9
10 => 5
\$\endgroup\$
0
\$\begingroup\$

Perl 5 (5.12+), 32 bytes

say oct reverse sprintf"%bb0",<>

(Input on stdin, output on stdout, requires -E or -M5.012 at no cost).

Straightforward but not all that short. Too bad "reverse" and "sprintf" are such weighty keywords.

oct is an odd legacy name; oct "123" gives the decimal equivalent of octal 123 as you'd expect, but oct "0x123" interprets its input as hex and oct "0b101" interprets it as binary.

\$\endgroup\$
  • 1
    \$\begingroup\$ You can shave a couple of characters off this by including the 0b in the sprintf statement: say oct reverse sprintf"%bb0",<> \$\endgroup\$ – Xcali Oct 22 '17 at 3:07
0
\$\begingroup\$

Common Lisp, 52 bytes

(parse-integer(reverse(format()"~b"(read))):radix 2)

Try it online!

\$\endgroup\$
0
\$\begingroup\$

C 41 bytes

g(i,r){for(r=0;r+=r+i%2,i/=2;);return r;}

Input in "i" output the result

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Labyrinth, 22 bytes

_2/?+:{!
}    "
++:{%#

Try it online!

Explanation

The idea is to disassemble the input bit-by-bit while assembling the output from the other end. Luckily, it's easiest to deconstruct a number from the right, and build one up from the left, so this automatically reverses the bits. We'll generally be keeping what's left of the input on top the main stack, and what we've already computed of the result on top of the auxiliary stack.

_2/  When the program starts out, this doesn't really do anything, because it
     just divides an implicit zero by 2.
?+   Read an integer N from STDIN and add it to the implicit zero on top of 
     the stack.

     The main loop starts here:

:    Duplicate what's left of N. This is also used as the conditional to end
     the loop. Once this reaches zero, the IP moves straight ahead, exiting
     the loop. Otherwise, the IP turns south which continues the loop.
#    Push the stack depth, 2.
%    Take N modulo 2, i.e. get its least significant bit.
{    Fetch the intermediate result R from the auxiliary stack.
:+   Double it (shifting its existing bits left by one position).
+    Add the bit we just extracted from N to R.
}    Put R back on the auxiliary stack.
_2/  Divide N by 2, dropping its least significant bit.
?+   We're at EOF, so ? just pushes zero and the + gets rid of that zero.

     Then the main loop starts over.
     When we exit the loop (once N is zero), this bit is run:

{    Retrieve R from the auxiliary stack.
!    Print it.
     The IP hits a dead end and turns around.
{:+? Various shenanigans which simply leave a zero on top of the stack.
/    Terminates the program due to the attempted division by zero.
\$\endgroup\$
0
\$\begingroup\$

APL (Dyalog Unicode), 10 bytes

2⊥∘⊖2∘⊥⍣¯1

Try it!

Thanks to @Adám for 2 bytes.

How it works:

This is a tacit function. To use it, it has to be assigned a name (like f←) and then called over an input; for the test cases: f 1, f 2, etc.

2⊥∘⊖2∘⊥⍣¯1  # Main function; tacit.
       ⍣¯1  # invert
    2∘⊥     # convert from base 2 (which is inverted to 'convert to base 2')
  ∘⊖        # flip, then
2⊥          # convert from base 2 
\$\endgroup\$
0
\$\begingroup\$

Husk, 3 bytes

ḋ↔ḋ

Try it online!

Explanation

Here's an explanation, even if there's not much to it:

     -- implicit input N    | 10
  ḋ  -- convert to base2    | [1,0,1,0]
 ↔   -- reverse             | [0,1,0,1]
ḋ    -- convert from base2  | 5
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 44 bytes

f=i=>(a=0,(x=i=>i?(a=a*2+i%2,x(i>>1)):a)(i))

for(i=1;i<10;i++){console.log(i,f(i))}

\$\endgroup\$
0
\$\begingroup\$

Add++, 14 bytes

D,f,@,BBBR2@Bb

Try it online!

How it works

D,f,@,   - Create a monadic function named f. Example argument: [10]
      BB - Convert to binary;     STACK = ['1010']
      BR - Reverse the top value; STACK = ['0101']
      2  - Push 2;                STACK = ['0101' 2]
      @  - Reverse the stack;     STACK = [2 '0101']
      Bb - Convert from base;     STACK = [5]
         - Implicit return
\$\endgroup\$
0
\$\begingroup\$

Julia, 32 bytes

f(n)=parseint(reverse(bin(n)),2)

gives a warning but still runs

\$\endgroup\$
  • 1
    \$\begingroup\$ Is this a full program or a function, because it looks like a snippet? If this is a snippet, you can change it so that it conforms with our rules. \$\endgroup\$ – caird coinheringaahing Oct 25 '17 at 20:00
  • \$\begingroup\$ if you run this exact code on the interpreter it returns the value. If it must return using the return keyword, I will add that in. other than that, and input, this is a full program. just substitute n for any number (input was not specified in the rules, unless thats a default requirement) \$\endgroup\$ – EricShermanCS Oct 25 '17 at 20:07
0
\$\begingroup\$

RProgN 2, 6 bytes

2Bi2iB

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Scala 47 bytes

Handles BigInt

((i:BigInt)=>BigInt(i.toString(2).reverse,2))([Number to Reverse])

if only we could:

(i=>BigInt(i.toString(2).reverse,2))([Number to Reverse])

or

(BigInt(_.toString(2).reverse,2))([Number to Reverse])

Example (REPL):

scala> ((i:Int)=>BigInt(i.toString(2).reverse,2))(100)
res1: scala.math.BigInt = 19

Example (in Situ):

object main extends App {
    val arg = Option(args).getOrElse(Array[String]("100"))
    (BigInt(arg(0)) to BigInt(arg(1))).map((n)=>
    (println(n + "-->" + BigInt(n.toString(2).reverse, 2))))
}

run:

run 20 30

result:

[debug] Waiting for thread run-main-23 to terminate.
20-->5
21-->21
22-->13
23-->29
24-->3
25-->19
26-->11
27-->27
28-->7
29-->23
30-->15
[debug]         Thread run-main-23 exited.
\$\endgroup\$
0
\$\begingroup\$

REXX, 46 bytes

say x2d(b2x(reverse(trunc(x2b(d2x(arg(1)))))))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.