# 反向（二进制）位数是多少？

33

### 例子：

``````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)
``````

2
“反转位”是否意味着反转其二进制数字？有时，这也可能意味着反转每一点
ETHproductions

juniorRubyist

Geobits

orlp

1
“以10为基数”为何有任何特定原因？
CalculatorFeline

20

# Python，29个字节

``lambda n:int(bin(n)[:1:-1],2)``

2

mbomb007'1

4

6
@ mbomb007，所以我的答案无效，因为您在手前9秒钟单击了发布按钮？仅仅因为我们同时达到相同的高尔夫水平并不意味着我们必须删除任何答案。如果有的话，归咎于零努力问题。
FlipTack

3

mbomb007'1

1
@steenbergh谁在乎？相同的代码，相同的分数。
mbomb007 '17

13

## JavaScript（ES6），30 28字节

@Arnauld节省了2个字节

``````f=(n,q)=>n?f(n>>1,q*2|n%2):q
``````

``````n=>+[...n.toString(2),'0b'].reverse().join``
``````

``````f=(n,q='0b')=>n?f(n>>1,q+n%2):+q
``````

`f=(n,q)=>n?f(n>>1,q*2|n%2):q`几乎可以工作。但可惜不是`n=0`
Arnauld

@Arnauld OP尚未回答输入是否将始终为正，但如果是，则不必处理0。
FlipTack

Arnauld

@Arnauld谢谢！
ETHproductions

10

# Java 8，53 47 46 45字节

• -4字节感谢Titus
• -1字节感谢Kevin Cruijssen

``x->{int t=0;for(;x>0;x/=2)t+=t+x%2;return t;}``

``````x -> {
int t = 0;           // Initialize result holder
while (x > 0) {      // While there are bits left in input:
t <<= 1;         //   Add a 0 bit at the end of result
t += x%2;        //   Set it to the last bit of x
x >>= 1;         //   Hack off the last bit of x
}
return t;            // Return the final result
};``````

1

2
@Titus并非没有明确转换为布尔值，但是感谢其他技巧！也刚刚意识到`x>>=1`可以被替换`x/=2`为它将自动被整数除法。
FlipTack

45字节（更改`t=t*2+``t+=t+`。）

@KevinCruijssen不错！
FlipTack

9

# J，6个字节

``````|.&.#:
``````

`|.` 相反

`&.`

`#:` 基数2

8

# 果冻，3个字节

``````BUḄ
``````

``````B   # convert to binary
U  # reverse
Ḅ # convert to decimal
``````

7

Cyoce

aioobe

1
@aioobe是的。Jelly使用自己的代码页，其中每个字符均为1个字节。

aioobe

8

## Mathematica，19个字节

``````#~IntegerReverse~2&
``````

7

# 迷宫，23字节

``````?_";:_2
:   %
@/2_"!
``````

1

ETHproductions

1

6

# C，48 44 43 42字节

-1字节归功于gurka，-1字节归功于anatolyg：

``r;f(n){for(r=n&1;n/=2;r+=r+n%2);return r;}``

``r;f(n){r=n&1;while(n/=2)r=2*r+n%2;return r;}``

``r;f(n){r=0;while(n)r=2*(r+n%2),n/=2;return r/2;}``

``````r;
f(n){
for(
r=n&1;
n/=2;
r+=r+n%2
);
return r;}
}

main() {
#define P(x) printf("%d %d\n",x,f(x))
P(1);
P(2);
P(3);
P(4);
P(5);
P(6);
P(7);
P(8);
P(9);
P(10);
}``````

`r`此处是否尚未初始化为零`r;f(n){r=0;`，例如`r=0;`不必要？也是次要的错字：“以前的48字节解决方案”
simon

1
@gurka该功能应可重用。
Karl Napf '17

1

anatolyg'1

@anatolyg是这样的：`r;f(n){for(r=n&1;n/=2;r=2*r+n%2);return r;}`？短1个字节，但是我不确定它是否为有效的C（C99）。
simon

anatolyg

5

# Ruby，29个 28个字节

``````->n{("%b"%n).reverse.to_i 2}
``````

“％b”％n将输入n格式化为二进制字符串，取反，然后转换回数字

``````m=->n{("%b"%n).reverse.to_i 2}
m #=> 1
m #=> 1
m #=> 3
m #=> 1
m #=> 5
m #=> 3
m #=> 7
m #=> 1
m #=> 9
m #=> 5
``````

@Titus我认为您误解了答案。`2`是他转换的基础，`n`也是输入。`->args{return value}`是ruby lambda语法
Cyoce

Cyoce

@Cyoce足够肯定，谢谢。

4

# Java（OpenJDK），63个字节

``a->a.valueOf(new StringBuffer(a.toString(a,2)).reverse()+"",2);``

FlipTack

@FlipTack糟糕。在我记得那个副本存在之前，它最初是一个函数
Pavel

1

FlipTack

1
`StringBuffer`保存一个字节以上`StringBuilder`

1

Cyoce

3

# Perl 6，19个字节

``````{:2(.base(2).flip)}
``````

2
Perl 6 a Block中的@Titus是一种代码，也就是说它是可调用的对象。上面是一个表达式，您可以采用该表达式并将其分配给其他语言的函数或lambda之类的变量，或直接调用- `{:2(.base(2).flip)}(10)`在REPL处将显示5。因此，它符合该函数的标准代码高尔夫球准则。
hobbs

3

``````0!b=b
a!b=div a 2!(b+b+mod a 2)
(!0)
``````

3

# PHP，33字节

``<?=bindec(strrev(decbin(\$argn)));``

``for(;\$n=&\$argn;\$n>>=1)\$r+=\$r+\$n%2;echo\$r;``

``function r(\$n,\$r=0){return\$n?r(\$n>>1,\$r*2+\$n%2):\$r;}``

@JörgHülsermann44个字节有`\$r+=\$r`。但是我实际上不记得为什么把它放在前面。

2

# MATL，4个字节

``````BPXB
``````

### 说明

``````B     % Input a number implicitly. Convert to binary array
P     % Reverse array
XB    % Convert from binary array to number. Display implicitly
``````

2

# Pyth，6个字节

``````i_.BQ2
``````

### 说明

``````i_.BQ2
Q     eval(input())
.B      convert to binary
_        reverse
i    2    convert from base 2 to base 10
``````

2

# Scala, 40 bytes

``````i=>BigInt(BigInt(i)toString 2 reverse,2)
``````

### Usage:

``````val f:(Int=>Any)=i=>BigInt(BigInt(i)toString 2 reverse,2)
f(10) //returns 5
``````

### Explanation:

``````i =>          // create an anonymous function with a parameter i
BigInt(       //return a BigInt contructed from
BigInt(i)     //i converted to a BigInt
toString 2    //converted to a binary string
reverse       //revered
,
2             //interpreted as a binary string
)
``````

1

# Mathematica, 38 bytes

``````#+##&~Fold~Reverse[#~IntegerDigits~2]&
``````

1

# Groovy, 46 bytes

``````{0.parseInt(0.toBinaryString(it).reverse(),2)}
``````

Does this take any input?
Titus

1
@Titus `it` refers to the argument given to a block IIRC
Cyoce

I love how this is the same length as my Java answer - Java and groovy, unite!
FlipTack

1
@FlipTack I'm gonna go cry now.
Magic Octopus Urn

1

# CJam, 8 bytes

``````ri2bW%2b
``````

Try it online!

### Explanation

``````ri          e# Read integer
2b        e# Convert to binary array
W%      e# Reverse array
2b    e# Convert from binary array to number. Implicitly display
``````

1

## Batch, 62 bytes

``````@set/an=%1/2,r=%2+%1%%2
@if %n% gtr 0 %0 %n% %r%*2
@echo %r%
``````

Explanation: On the first pass, `%1` contains the input parameter while `%2` is empty. We therefore evaluate `n` as half of `%1` and `r` as `+%1` modulo 2 (the `%` operator has to be doubled to quote it). If `n` is not zero, we then call ourselves tail recursively passing in `n` and an expression that gets evaluated on the next pass effectively doubling `r` each time.

1

# C#, 98 bytes

``````using System.Linq;using b=System.Convert;a=>b.ToInt64(string.Concat(b.ToString(a,2).Reverse()),2);
``````

1

## R, 55 bytes

``````sum(2^((length(y<-rev(miscFuncs::bin(scan()))):1)-1)*y)
``````

Reads input from stdin and consequently uses the `bin` function from the `miscFuncs` package to convert from decimal to a binary vector.

1

# Pushy, 19 bytes

No builtin base conversion!

``````\$&2%v2/;FL:vK2*;OS#
``````

Try it online!

Pushy has two stacks, and this answer makes use of this extensively.

There are two parts two this program. First, `\$&2%v2/;F`, converts the number to its reverse binary representation:

``````            \ Implicit: Input is an integer on main stack.
\$      ;    \ While i != 0:
&2%v       \   Put i % 2 on auxiliary stack
2/     \   i = i // 2 (integer division)
F   \ Swap stacks (so result is on main stack)
``````

Given the example 10, the stacks would appear as following on each iteration:

``````1: 
2: []

1: 
2: 

1: 
2: [0, 1]

1: 
2: [0, 1, 0]

1: 
2: [0, 1, 0, 1]
``````

We can see that after the final iteration, `0, 1, 0, 1` has been created on the second stack - the reverse binary digits of 10, `0b1010`.

The second part of the code, `L:vK2*;OS#`, is taken from my previous answer which converts binary to decimal. Using the method decsribed and explained in that answer, it converts the binary digits on the stack into a base 10 integer, and prints the result.

0

# k, 18 bytes

``````{2/:|X@&|\X:0b\:x}
``````

Example:

``````k){2/:|X@&|\X:0b\:x}6
3
``````

0

# C#, 167 bytes

`````` for(int i = 1; i <= 10; i++)
{
var bytes= Convert.ToString(i, 2);
var value= Convert.ToInt32(byteValue.Reverse());
console.WriteLine(value);
}
``````

Explanation:

Here I will iterate n values and each time iterated integer value is convert to byte value then reverse that byte value and that byte value is converted to integer value.

1
Welcome to the site! I don't know much about C# but you most certainly have a good deal of extra whitespace I would recommend removing. It also is not clear how I/O is dealt with in this submission. It is standard to either write a function or to use `STDIN` (I think that is `console.Read()` but you would probably know better than I would) and `STDOUT`. Anyway, welcome to the site if you want more experienced advice in golfing C# I would recommend codegolf.stackexchange.com/questions/173/…
Wheat Wizard

I've downvoted this answer, because it doesn't work at all. `.Reverse()` returnes `IEnumerable<char>`. As `Convert.ToInt32` doesn't have an overload for IEnumerable it throws an exception. Also the answer doesn't follow the rules for code golf: 1)As nothing is specified the submission has to be a full program or function not just a snippet. 2)`using` statements must be included in the byte count
raznagul

0

c/c++ 136 bytes

``````uint8_t f(uint8_t n){int s=8*sizeof(n)-ceil(log2(n));n=(n&240)>>4|(n&15)<<4;n=(n&204)>>2|(n&51)<<2;n=(n&172)>>1|(n&85)<<1;return(n>>s);}
``````

It's not going to win, but I wanted to take a different approach in c/c++ 120 bytes in the function

``````#include <math.h>
#include <stdio.h>
#include <stdint.h>

uint8_t f(uint8_t n){
int s=8*sizeof(n)-ceil(log2(n));
n=(n&240)>>4|(n&15)<<4;
n=(n&204)>>2|(n&51)<<2;
n=(n&172)>>1|(n&85)<<1;
return (n>>s);
}

int main(){
printf("%u\n",f(6));
return 0;
}
``````

To elaborate on what I am doing, I used the log function to determine the number of bits utilized by the input. Than a series of three bit shifts left/right, inside/outside, even/odd which flips the entire integer. Finally a bit shift to shift the number back to the right. Using decimals for bit shifts instead of hex is a pain but it saved a few bytes.

You do need to include the function declaration, so this is actually 163 bytes. Although, if you remove the extraneous whitespace, you could shorten it to 136.
DJMcMayhem