リバース(バイナリ)ビット番号とは何ですか?


33

あなたが与えられているので、POSITIVEのベース10(10進数)の数を。あなたの仕事は、2進数を逆にし、その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)

これは課題なので、使用するバイト数が最も少ないソリューションが勝ちます。

これはA030101です、OEISのです。


2
「ビットを逆にする」とは、2進数を逆にすることを意味しますか?時には、それはすべてのビットを反転させることも意味します。
— -ETHproductions

はい。不明確で申し訳ありません。
— juniorRubyist

これとこれは似たようなものです。
— ジオビット


1
「ベース10」特別な理由は何ですか?
— 電卓

回答:


20

Python、29バイト

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

オンラインでお試しください!

これは、結果を返す匿名の名前のない関数です。


最初にbin(n)、引数をバイナリ文字列に変換します。通常、スライス表記でこれを逆にします[::-1]。これは、-1のステップで、つまり逆方向に文字列を読み取ります。ただし、Pythonのバイナリ文字列には接頭辞が付いている0bため、スライスの2番目の引数に1を指定します。これにより、Pythonはインデックス1で終了し、インデックス1と0を読み取らないようになります。

後方バイナリ文字列ができたのでint(...)、2番目の引数に2を渡して渡します。これは文字列を基数2の整数として読み取り、ラムダ式によって暗黙的に返されます。


2
あなたを9秒倒します。
— mbomb007


6
@ mbomb007だから、あなたは9秒前に投稿ボタンをクリックしたので私の答えは無効ですか?同じゴルフに同時に行ったからといって、答えを削除する必要はありません。どちらかといえば、ゼロエフォートの質問のせいだ。
— FlipTack

3
無効ではありませんが、間違いなく無意味です。私が遅かったなら、私は単に私のものを削除し、私もそれを思いついたより速いものにコメントを投稿するでしょう。
— mbomb007

1
@steenbergh誰が気にしますか?同じコード、同じスコア。
— mbomb007


13

JavaScript(ES6)、30 28バイト

@Arnauldのおかげで2バイト節約

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

これは、基本的に一度に1ビットの逆を計算します。q= 0から始めます。一方、nが正である、我々は乗算Qのオフ最後のビットサーバ2によって、n個と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 OPは、入力が常に正であるかどうかについてまだ回答していませんが、そうであれば、0を処理する必要はありません。
— FlipTack

これは遅いフォローアップですが、入力は常に正であることが知られています。
— アーナルド

@Arnauldありがとう!
— -ETHproductions

10

Java 8、53 47 46 45バイト

  • Titusのおかげで-4バイト
  • -1バイト、Kevin Cruijssenに感謝

これは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+。)
— ケビンCruijssen

@KevinCruijssenいいね!
— FlipTack




7

ラビリンス、23バイト

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

まあ、これは厄介です...これは逆バイナリ番号を返します...私のバグと私のID 10Tエラーの両方を指摘してくれた@Martin Enderに感謝します。したがって、これは機能しません。別の解決策を見つける必要があります。


1
PPCGへようこそ、最初の投稿です!ラビリンスのような言語でチャレンジを完了することは非常に難しい場合があります。ここでは、通常、回答の最初の行の先頭に1つまたは2つのハッシュを付けて、ヘッダーとして表示します# Labyrinth, 89 bytes
— 。– ETHproductions

1
誤って2行目の先頭のスペースを省略しましたか?現状では、プログラムは_ジャンクション上にあるため、最初の行で前後にバウンドします。
— マーティンエンダー

残念ながら、チャレンジはバイナリ表現ではなく逆数の10進表現を要求するため、これは関係なく有効ではないことに気付きました。
— マーティンエンダー

6

C、48 44 43 42バイト

gurkaのおかげで-1バイト、anatolygのおかげで-1バイト:

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バイトソリューション」
— サイモン

1
@gurka関数は再利用可能でなければなりません。
— カールナップ

1
forループは常に少なくともwhileループと同じくらい短く、多くの場合より短いと思います。
— アナトリグ

@anatolygのようなもの:r;f(n){for(r=n&1;n/=2;r=2*r+n%2);return r;}?1バイト短くなりましたが、有効なC(C99)かどうかわかりません。
— サイモン

はい; また、ターン=に+=それが短く、より多くの難読化させるために
— anatolyg

5

ルビー、 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

@タイタスあなたは答えを誤解していると思います。2は変換先のベースでnあり、入力です。->args{return value}ルビーのラムダ構文です
— チョイス

の括弧を削除できます.to_i(2)か?
— チョイス

@Cyoce確かに、ありがとう。
— アレクシスアンデルセン


4

Java(OpenJDK)、63バイト

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

オンラインでお試しください!

-12バイトで突く、-8バイトでCyoceに感謝します!


REPLの送信は許可されていますが、入力が事前定義された変数(aこのコンテキストのように)にあるとは想定できないというルールに従います
— -FlipTack

@FlipTackおっと。私はREPLは存在していた覚えて前にそれはもともと関数であった
— パベル

1
また、将来的printにはprintln、ゴルフの代わりに使用してください:)
— FlipTack

1
StringBufferバイトを節約StringBuilder
— ポケ

1
+""代わりにできます.toString()か?
— チョイス

3

Perl 6、19バイト

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

入力はどこにありますか?
— タイタス

これは、単一のパラメーターを受け取る関数です$_。名前では言及されていませんが、baseメソッドが呼び出されます。
— ショーン

2
Perl 6の@Titusブロックはコードの一種で、呼び出し可能なオブジェクトです。上記は、他の言語の関数やラムダなどの変数に割り当てて割り当てることができる式、または直接呼び出す({:2(.base(2).flip)}(10)REPLで5を出力する)ため、関数の標準のコードゴルフ基準を満たしています。
— ホッブズ

3

Haskell、36バイト

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

Same algorithm (and length!) as ETHproductions’ JavaScript answer.



3

PHP, 33 bytes

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

convert to base2, reverse string, convert to decimal. Save to file and run as pipe with -F.

no builtins:

iterative, 41 bytes

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

While input has set bits, pop a bit from input and push it to output. Run as pipe with -nR.

recursive, 52 bytes

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

@JörgHülsermann The 44 bytes have $r+=$r. But I actually don´t remember why I put that in front.
— Titus

2

MATL, 4 bytes

BPXB

Try it online!

Explanation

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



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

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
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.