2的幂和


31

挑战

给定一个整数输入x其中1 <= x <= 255,返回时总结给出了两种力量的结果x

例子

给定输入:

86

您的程序应输出:

64 16 4 2

输入:

240

输出:

128 64 32 16

输入:

1

输出:

1

输入:

64

输出:

64

如果总和中没有确定的2的幂,则输出可能包含零。

例如,输入65可以输出0 64 0 0 0 0 0 1

计分

这是,因此每种语言中最短的答案将获胜。


5
列表是否必须从高到低排序?
阿达姆(Adám)

2
我们可以输出一些冗余零吗?
乔纳森·艾伦

4
RE:“从高到低排序”为什么要添加一个限制,该限制不属于挑战范围,并且会使大多数现有答案无效?(还有little-endian呢?!)+由于集合没有任何顺序,它使我的Python答案无效。
乔纳森·艾伦

5
@JonathanAllan我已取消限制。下次发布其他问题时,我会记住这一点-我对此还很陌生。:)
SpookyGengar

6
我认为您可能想声明任何2的幂只能使用一次。否则,可能会有人对输入输出3“1 1 1”
黑色猫头鹰凯

Answers:


38

JavaScript (ES6), 28 bytes

f=n=>n?[...f(n&~-n),n&-n]:[]

Try it online!


9
You're the only person in the whole world who can make me upvote JavaScript answers!
sergiol

4
@sergiol, why wouldn't you normally upvote a JS solution? A good solution is a good solution regardless of the language used or who posted it.
Shaggy

@Shaggy Because Arnauld seems the only person to do such Javascript solutions. His answers are pure genius!
sergiol

3
@sergiol Thanks for the compliment, but that's not quite true. I'm regularly outgolfed by more clever answers -- and that's what this site is all about. ^^
Arnauld

@Oliver I'm not sure. It seems like leading zeros (before 128) are forbidden. Otherwise, another possible variant is f=n=>n&&f(n&~-n)+[,n&-n].
Arnauld

12

Pure Bash, 20

echo $[2**{7..0}&$1]

Try it online!

Explanation

          {7..0}     # Brace expansion: 7 6 5 4 3 2 1 0
       2**{7..0}     # Brace expansion: 128 64 32 16 8 4 2 1
       2**{7..0}&$1  # Brace expansion: 128&n 64&n 32&n 16&n 8&n 4&n 2&n 1&n (Bitwise AND)
     $[2**{7..0}&$1] # Arithmetic expansion
echo $[2**{7..0}&$1] # and output

12

Jelly, 4 bytes

-2 since we may output zeros in place of unused powers of 2 :)

Ḷ2*&

Try it online!

How?

Ḷ2*& - Link: integer, n         e.g. 10
Ḷ    - lowered range of n            [  0,  1,  2,  3,  4,  5,  6,  7,  8,  9]
 2*  - two to the power of           [  1,  2,  4,  8, 16, 32, 64,128,256,512]
   & - bit-wise and                  [  0,  2,  0,  8,  0,  0,  0,  0,  0,  0]

11

Jelly, 6 bytes

BUT’2*

Try it online!

Explanation

BUT here is an explanation (note: I had assumed that we may only output the powers of 2 themselves and nothing else):

BUT’2* – Monadic link. Takes a number N as input. Example: 86
B      – Convert N to binary.                              [1, 0, 1, 0, 1, 1, 0]
 U     – Reverse.                                          [0, 1, 1, 0, 1, 0, 1]
  T    – Truthy indices.                                   [2, 3, 5, 7]
   ’   – Decrement.                                        [1, 2, 4, 6]
    2* – Raise 2 to that power.                            [2, 4, 16, 64]

"Proof" that it works correctly. The standard representation of an integer X in base 2 is a list {x1,x2,x3,,xn}, where xi{0,1},i1,n¯, such that:

X=i=1nxi2ni
The indices i such that xi=0 obviously have no contribution so we're only interested in finding those such that xi=1. Since subtracting i from n is not convenient (the powers of two all have exponents of the form ni, where i is any index of a 1), instead of finding the truthy indices in this list we reverse it and then find them "backwards" with UT. Now that we've found the correct indices all we have to do is raise 2 to those powers.


1
"ASCII-only" Sneaky there...
Erik the Outgolfer

1
@EriktheOutgolfer I guess BUT2*H would work though.
Mr. Xcoder

1
Pretty impressive that this works with an input of 302231454903657293676544.
Michael Karas


8

APL (Dyalog Extended), 7 bytesSBCS

Anonymous tacit prefix function. Requires 0-based indexing (⎕IO←0).

2*⍸⍢⌽⍤⊤

Try it online!

2 two
* raised to the power of
 the ɩndices where true
 while
 reversed
 of
 the binary representation


8

Sledgehammer 0.2, 3 bytes

⡔⡸⢣

Decompresses into {intLiteral[2],call[NumberExpand,2]}.

Sledgehammer is a compressor for Wolfram Language code using Braille as a code page. The actual size of the above is 2.75 bytes, but due to current rules on meta, padding to the nearest byte is counted in code size.


2
Huh! Neat little language, and all the characters are actually printable.
LegionMammal978

And now I can't get the Peter Gabriel song out of my mind...
Digital Trauma

8

05AB1E, 3 bytes

Ýo&

Port of @JonathanAllan's Jelly answer, so make sure to upvote him!

Contains zeros (including -loads of- trailing zeros).

Try it online or verify all test cases.

Explanation:

Ý      # Create a list in the range [0, (implicit) input]
       #  i.e. 15 → [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
       #  i.e. 16 → [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
 o     # Take 2 to the power of each value
       #  → [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768]
       #  → [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536]
  &    # Bitwise-AND each value with the (implicit) input
       # 15 → [1,2,4,8,0,0,0,0,0,0,0,0,0,0,0,0]
       # 16 → [0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0]
       # (and output the result implicitly)

1
... what?! Never honestly seen bitwise and used in osabie. Nice one.
Magic Octopus Urn

@MagicOctopusUrn I indeed also don't use it very often. Can't even find any other answer I've used & in. xD I have used Bitwise-XOR a couple of times, like here or here and Bitwise-NOT once here (which I later removed again after golfing further..). I do use Bitwise-AND, XOR, OR, NOT, SHIFT, etc. pretty often in Java, but in 05AB1E not so much. :)
Kevin Cruijssen



7

R, 27 23 bytes

bitwAnd(scan(),2^(7:0))

Try it online!

Unrolled code and explanation :

A = scan()         # get input number A from stdin
                   # e.g. A = 65

bitwAnd( A , 2^(7:0))  # bitwise AND between all powers of 2 : 2^7 ... 2^0 and A
                       # and implicitly print the result
                       # e.g. B = bitwAnd(65, c(128,64,32,16,8,4,2,1)) = c(0,64,0,0,0,0,0,1)
  • 4 bytes thanks to @Kirill L.

1
23 bytes with bitwise and.
Kirill L.

@KirillL.: brilliant !
digEmAll

7

C# (Visual C# Interactive Compiler), 29 bytes

Contains 5 unprintable characters.

n=>"€@ ".Select(a=>a&n)

Explanation

//Lambda taking one parameter 'n'
n=>
//String with ASCII characters 128, 64, 32, 16, 8, 4, 2, and 1
"€@ "
//Iterate through all the chars of the above string and transform them to
.Select(a=>
//A bitwise AND operation between the integer value of the current char and the input value
a&n)

Try it online!


But we need to get rid of zeros, like n=>new int[8].Select((j,i)=>1<<i&n).Where(i=>i!=0) The part before Where is five bytes shorter btw
polfosol ఠ_ఠ

@polfosol The output may contain zeros
Jo King

2
@JoKing Still, n=>new int[8].Select((j,i)=>1<<i&n) is 35 bytes long and we won't need additional flags and text encodings.
polfosol ఠ_ఠ

1
Using ascii characters 0-7 should be shorter, eg n=>"INSERT ASCII HERE".Select(a=>1<<a&n) But I'm on a mobile device that can't display or type unprintables, so I'll have to wait till I get home to update the answer
Embodiment of Ignorance

6

C# (Visual C# Interactive Compiler), 38 bytes

x=>{for(int y=8;y-->0;Print(x&1<<y));}

Try it online!



1
Fails for inputs 1, 2, 4, 8, 16, etc. (the x>y should be x>=y instead).
Kevin Cruijssen

1
@ASCIIOnly - I'm telling you, the range operator is going to be sweet :)
dana

@ASCII-only Mean while, you can use the flag /u:System.Linq.Enumerable and try this for 31 bytes
Embodiment of Ignorance

@EmbodimentofIgnorance sure. but i'd prefer not to list language as "C# /u:System.Linq.Enumerable" :P
ASCII-only


5

05AB1E, 7 bytes

2вRƶ<oò

explanation:

2в        convert input to binary array
R         reverse array
ƶ<        multiply each item by it's index and subtract 1
oò        2^item then round down

Try it online!


Also works with input of 302231454903657293676544
Michael Karas



5

C (clang), 133 110 63 58 bytes

58-byte solution thanks to @ceilingcat.

x=256;main(y){for(scanf("%d",&y);x/=2;)printf("%d ",y&x);}

Try it online!


In C89, you can declare like main(){} and the return type defaults to int. Same for variables at global scope. Also, at least on normal implementations like clang, printf and scanf work without prototypes. You get warnings of course, but it's still valid C89 (maybe) or at least K&R C for them to be implicitly declared. The types of the C objects you pass as args defines how they're passed, so a char* and int* will Just Work without truncating pointers to 32-bit on x86-64 or anything. (Default argument promotions happen, same as for variadic functions which they are anyway.)
Peter Cordes

Or is this aiming to be valid C11 with no undefined behaviour? If so, proudly proclaim it. :) And BTW, writing a function that takes an output array as an arg would probably be smaller. Anyway, see Tips for golfing in C
Peter Cordes

You can use bitwise & to check if a bit is set. Like y&(1<<x)&&printf("%d ",1<<x);. Or to not skip zeros, just printf("%d ", y&(1<<x)). Or instead of counting bit positions, use x=256 and x>>=1 to shift the mask. main(y){int x=256;for(scanf("%d",&y);x>>=1;)printf("%d ",y&x);} 63 bytes Try it online! clang will even compile that with -std=c11
Peter Cordes


4

MATL, 5 bytes

BPfqW

Try it online!

Explanation

Consider input 86 as an example.

B    % Implicit input. Convert to binary (highest to lowest digits)
     % STACK: [1 0 1 0 1 1 0]
P    % Flip
     % STACK: [0 1 1 0 1 0 1]
f    % Find: indices of nonzeros (1-based)
     % STACK: [2 3 5 7]
q    % Subtract 1, element-wise
     % STACK: [1 2 4 6]
W    % Exponential with base 2, element-wise. Implicit display
     % STACK: [2 4 16 64]

4

Perl 6, 16 12 bytes

-4 bytes thanks to Jonathan Allan

*+&2**all ^8

Try it online!

Returns an All Junction with 8 elements. This is a rather non-standard way of returning, but generally, Junctions can act as ordered (at least until autothreading is implemented) lists and it is possible to extract the values from one.

Explanation:

*+&              # Bitwise AND the input with
   2**           # 2 raised to the power of
      all ^8     # All of the range 0 to 7

4

Japt, 8 5 bytes

Æ&2pX

Try it

Æ&2pX     :Implicit input of integer U
Æ         :Map each X in the range [0,U)
 &        :  Bitwise AND of U with
  2pX     :  2 to the power of X

Alternative

Suggested by Oliver to avoid the 0s in the output using the -mf flag.

N&2pU

Try it

N&2pU     :Implicitly map each U in the range [0,input)
N         :The (singleton) array of inputs
 &        :Bitwise AND with
  2pX     :2 to the power of U
          :Implicitly filter and output

1
Nice one. You can do N&2pU with -mf to avoid the 0s
Oliver




4

K (oK), 19 16 bytes

-3 bytes thanks to ngn!

{*/x#2}'&|(8#2)\

Try it online!

oK does not have power operator, that's why I need a helper function {*/x#2} (copy 2 x times and reduce the resulting list by multiplication)


you can omit the { x}
ngn

@ngn Thanks! I tried it and it worked, but I wasn't sure it is acceptible.
Galen Ivanov

4

Alchemist, 125 bytes

_->In_x+128a+m
m+x+a->m+b
m+0x+a->n+a
m+0a->o+Out_b+Out_" "
n+b->n+x+c
n+0b+a->n+c
n+0a->p
o+b->o+c
o+0b->p
p+2c->p+a
p+0c->m

Try it online! or Test every input!

Explanation

_->In_x+128a+m           # Initialize universe with input, 128a (value to compare to) and m (state)
m+x+a->m+b               # If c has been halved, subtract min(a, x) from a and x and put its value into b
m+0x+a->n+a              # If x < a, continue to state n
m+0a->o+Out_b+Out_" "    # Else print and continue to state o
n+b->n+x+c               # Add min(a, x) (i.e. x) back to x, and add it to c (we're collecting a back into c)
n+0b+a->n+c              # Then, add the rest of a to c
n+0a->p                  # Then, go to state p
o+b->o+c                 # Add min(a, x) (i.e. a) to c - x _is_ greater than a and so contains it in its binary representation, so we're not adding back to x
o+0b->p                  # Then, go to state p
p+2c->p+a                # Halve c into a
p+0c->m                  # Then go to state m

4

PHP, 41 39 bytes

for($c=256;$c>>=1;)echo$argv[1]&$c,' ';

Try it online!

Or 38 with no fun >>= operator and PHP 5.6+:

for($x=8;$x--;)echo$argv[1]&2**$x,' ';

Or 36 with little-endian ("0 2 4 0 16 0 64 0") output:

while($x<8)echo$argv[1]&2**$x++,' ';

Really I just wanted to use the >>= operator, so I'm sticking with the 39.

Tests:

$php pow2.php 86
0 64 0 16 0 4 2 0

$php pow2.php 240
128 64 32 16 0 0 0 0

$php pow2.php 1
0 0 0 0 0 0 0 1

$php pow2.php 64
0 64 0 0 0 0 0 0

$php pow2.php 65
0 64 0 0 0 0 0 1

4

TSQL, 43 39 bytes

Can't find a shorter fancy solution, so here is a standard loop. -4 bytes thanks to MickyT and KirillL

DECLARE @y int=255

,@ int=128s:PRINT @y&@ SET @/=2IF @>0GOTO s

Try it out


using the bitwise and (&) you can save a few with the following ,@ int=128s:print @y&@ set @/=2IF @>0GOTO s. This is hinted by @KirillL for the R answer
MickyT

@MickyT that worked like a charm. Thanks a lot
t-clausen.dk


3

C# (Visual C# Interactive Compiler), 33 bytes

n=>{for(;n>0;n&=n-1)Print(n&-n);}

Port of @Arnauld's JavaScript (ES6) answer, so make sure to upvote him!

Try it online.

Explanation:

n=>{            // Method with integer parameter and no return-type
  for(;n>0      //  Continue looping as long as `n` is larger than 0:
      ;         //    After every iteration:
       n&=n-1)  //     Bitwise-AND `n` by `n-1`
    Print(      //   Print with trailing newline:
      n&-n);}   //    `n` bitwise-AND `-n`
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.