37
\$\begingroup\$

The Challenge

Given a list of integers, the "bittiest" number among them is the one with the most bits on - that is, the largest amount of bits set to 1 in its 32-bit two's complement representation.

Write a function (or a program) that takes as input a list of integers between \$ -2^{31} \$ and \$ 2^{31}-1 \$ (the range of 32-bit signed integers) and returns as output the "bittiest" number among them.

You may assume the list has at least one item.

Test Cases

1, 2, 3, 4 => 3
123, 64, 0, -4 => -4
7, 11 => either 7 or 11
1073741824, 1073741823 => 1073741823

Good Luck!

This is code golf, so the shortest program in bytes wins.

\$\endgroup\$
23
  • 3
    \$\begingroup\$ If our language has no 32-bit signed integers should we accept integers (and perform manipulations) or may we accept a list of ones and zeros (what a 32-bit signed integer actually is under the hood)? \$\endgroup\$ Commented Dec 19, 2020 at 20:42
  • 3
    \$\begingroup\$ I'd suggest adding larger test cases where it matters that we're using 32-bit signed integers for two's complement, and not say 16 or 64. \$\endgroup\$
    – xnor
    Commented Dec 19, 2020 at 22:38
  • 11
    \$\begingroup\$ @Bip, one of the standard rules around here is not to assume anything about the functionality of a language. There are languages where integers are unsigned, other sizes, or don't exist at all. It's not necessarily a primitive data type. \$\endgroup\$
    – Xcali
    Commented Dec 19, 2020 at 23:49
  • 13
    \$\begingroup\$ I think a clearer way to specify the challenge without making language assumptions is to say the input is a list of integers between -2^31 and 2^31-1, and we output one whose 32-bit signed representation has the most 1's. \$\endgroup\$
    – xnor
    Commented Dec 20, 2020 at 0:04
  • 4
    \$\begingroup\$ @qwr But then its inverse would not be the "itty-bittiest number". \$\endgroup\$
    – beaker
    Commented Dec 21, 2020 at 16:51

32 Answers 32

1
2
1
\$\begingroup\$

K4, 15 bytes

Solution:

{*x@>+/+0b\:'x}

Explanation:

Pretty much exactly the same as the ngn/k solution:

{            x} / lamdba taking implicit argument x
        0b\:'   / convert (0b \:) each (') to binary representation
       +        / flip (transpose)
     +/         / sum (+) over (/)
    >           / indices to sort descending
  x@            / apply indices to input x
 *              / take the first
\$\endgroup\$
0
\$\begingroup\$

Julia 1.0, 28 bytes

x->x[argmax(count_ones.(x))]

Try it online!

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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