反向(二进制)位数是多少?


33

因此,您将获得一个以10 为基数的数。您的工作是反转二进制数字并返回该基数10。

例子:

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)

这是一个挑战,因此使用最少字节数的解决方案将获胜。

这是OEIS中的A030101


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

是。抱歉,不清楚。
juniorRubyist

这个这个 veeeeery相似。
Geobits


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

Answers:


20

Python,29个字节

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

在线尝试!

这是一个匿名的,未命名的函数,它返回结果。


首先,bin(n)将参数转换为二进制字符串。通常,我们将使用切片符号将其反转[::-1]。这将以-1的步长读取字符串,即向后读取。但是,Python中的二进制字符串以开头0b,因此我们将切片的第二个参数设置为1,告诉Python向后读取终止于索引1的内容,因此不读取索引10

现在我们有了向后的二进制字符串,我们将其传递给int(...)第二个参数为2。这会将字符串读取为以2为底的整数,然后由lambda表达式隐式返回。


2
打败你9秒。
mbomb007'1


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

这基本上一次计算一次反向:我们从q = 0开始;而Ñ是积极的,我们乘q 2,服务器关闭的最后一位ñn>>1,并将其添加到q|n%2。当n达到0时,该数字已成功反转,我们返回q

得益于JS内置的长名称,轻松解决此难题需要44个字节:

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

使用递归和字符串,您可以得到一个执行相同操作的32字节解决方案:

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

这是一个lambda表达式,其原理与ETH的答案相同(尽管递归在Java中本来就太冗长,所以我们改为循环执行):

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

在线尝试!

可以使用进行分配IntFunction<Integer> f = ...,然后使用进行调用f.apply(num)。展开,展开和注释,如下所示:

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
将计算从循环头移到循环体,再用t*2而不是节省3个字节(t<<1)。您可以使用x代替x>0条件吗?
泰特斯

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

45字节(更改t=t*2+t+=t+。)
凯文·克鲁伊森

@KevinCruijssen不错!
FlipTack

9

J,6个字节

|.&.#:

|. 相反

&.

#: 基数2




7

迷宫,23字节

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

好吧,这很尴尬...这将返回反向二进制数...感谢@Martin Ender指出了我的错误和ID 10T错误。所以这行不通,我必须找到另一个解决方案。


1
欢迎来到PPCG,也不错!仅用迷宫之类的语言完成挑战可能非常困难。在这里,我们通常在答案的第一行之前添加一个或两个哈希值,以使其显示为标题:# Labyrinth, 89 bytes
ETHproductions

1
您是否意外地忽略了第二排的前导空格?就目前而言,该程序只是在第一行上来回跳动,因为_它们在交界处。
马丁·恩德

不幸的是,我只是注意到无论如何这都是无效的,因为挑战要求反向编号以10为基数表示,而不是二进制表示。
马丁·恩德

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;}

以前的44字节解决方案:

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

以前的48字节解决方案:

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
我认为for循环总是至少与while循环一样短,并且通常更短。
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] #=> 1
m[2] #=> 1
m[3] #=> 3
m[4] #=> 1
m[5] #=> 5
m[6] #=> 3
m[7] #=> 7
m[8] #=> 1
m[9] #=> 9
m[10] #=> 5

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

您可以删除其中的括号.to_i(2)吗?
Cyoce

@Cyoce足够肯定,谢谢。
亚历克西斯·安德森


4

Java(OpenJDK),63个字节

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

在线尝试!

感谢-12字节的戳和-8字节的Cyoce!


即使允许REPL提交,它们仍然遵循以下规则:您不能假定输入使用预定义变量(例如a在这种情况下)
FlipTack

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

1
另外,将来也可以print代替println高尔夫球:)
FlipTack

1
StringBuffer保存一个字节以上StringBuilder

1
你能+""代替.toString()吗?
Cyoce

3

Perl 6,19个字节

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

输入在哪里?
泰特斯

这是一个带有单个参数的函数$_。它没有被提及,但base方法被调用了。
肖恩

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

3

Haskell,36个字节

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

与ETHproductions的JavaScript答案相同的算法(和长度!)。



3

PHP,33字节

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

转换为base2,反向字符串,转换为十进制。保存到文件并使用管道运行-F

没有内置函数:

迭代的,41个字节

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

当输入已设置位时,从输入弹出一个位并将其推入输出。与一起作为管道运行-nR

递归,52字节

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

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




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

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: [10]
2: []

1: [5]
2: [0]

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

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

1: [0]
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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.