title: Is the number binary-heavy?

text:
# Question
Title: Is the number binary-heavy?
An integer is binary-heavy if its binary representation contains more `1`s than `0`s while ignoring leading zeroes. For example 1 is binary-heavy, as its binary representation is simply `1`, however 4 is not binary heavy, as its binary representation is `100`. In the event of a tie (for example 2, with a binary representation of `10`), the number is not considered binary-heavy.

Given a positive integer as input, output a truthy value if it is binary-heavy, and a falsey value if it is not.

## Testcases

Format: `input -> binary -> output`

```
1          ->                                1 -> True
2          ->                               10 -> False
4          ->                              100 -> False
5          ->                              101 -> True
60         ->                           111100 -> True
316        ->                        100111100 -> True
632        ->                       1001111000 -> False
2147483647 ->  1111111111111111111111111111111 -> True
2147483648 -> 10000000000000000000000000000000 -> False

```

## Scoring

This is so fewest bytes **in each language** wins

# Answer
> 31 votes
# x86 Machine Code, 15 14 bytes

```
F3 0F B8 C1 0F BD D1 03 C0 42 2B D0 D6 C3

```

This is a function using Microsoft's \__fastcall calling convention (first and only parameter in ecx, return value in eax, callee is allowed to clobber edx), though it can trivially be modified for other calling conventions that pass arguments in registers.

It returns 255 as truthy, and 0 as falsey.

It uses the undocumented (but widely supported) opcode `salc`.

Disassembly below:

```
;F3 0F B8 C1
  popcnt eax, ecx ; Sets eax to number of bits set in ecx

;0F BD D1
  bsr edx, ecx    ; Sets edx to the index of the leading 1 bit of ecx

;03 C0
  add eax, eax

;42
  inc edx

;2B D0
  sub edx, eax

  ; At this point,
  ;   edx = (index of highest bit set) + 1 - 2*(number of bits set)
  ; This is negative if and only if ecx was binary-heavy.

;D6
  salc           ; undocumented opcode. Sets al to 255 if carry flag
                 ; is set, and to 0 otherwise.

;C3
  ret

```

Try it online!

Thanks to Peter Cordes for suggesting replacing `lzcnt` with `bsr`.

# Answer
> 20 votes
# Jelly, 5 bytes

```
Bo-SR

```

Yields non-empty output (truthy) or empty output (falsy).

Try it online!

### How it works

```
Bo-SR  Main link. Argument: n

B      Binary; convert n to base 2.
 o-    Compute the logical OR with -1, mapping 1 -> 1 and 0 -> -1.
   S   Take the sum s. We need to check if the sum is strictly positive.
    R  Range; yield [1, ..., s], which is non-empty iff s > 0.

```

# Answer
> 18 votes
# Python 2, 35 bytes

```
lambda n:max('10',key=bin(n).count)

```

Try it online!

### Old answer, 38 bytes

Outputs `0` as falsy and `-2` or `-1` as truthy

```
lambda n:~cmp(*map(bin(n).count,'10'))

```

Try it online!

# Answer
> 12 votes
# Octave, 18 bytes

```
@(n)mode(de2bi(n))

```

TIO doesn't work since the communications toolbox is not included. It can be tested on Octave-Online.

### How this works:

`de2bi` converts a decimal number to a binary numeric vector, not a string as `dec2bin` does.

`mode` returns the most frequent digit in the vector. It defaults to the lowest in case of a tie.

```
@(n)                % Anonymous function that takes a decimal number as input 'n'
    mode(        )  % Computes the most frequent digit in the vector inside the parentheses
         de2bi(n)   % Converts the number 'n' to a binary vector

```

# Answer
> 11 votes
# MATL, 3 bytes

```
BXM

```

Try it online!

I don't really know MATL, I just noticed that `mode` could work in alephalpha's Octave answer and figured there was some equivalent in MATL.

```
B   ' binary array from input
 XM ' value appearing most.  On ties, 0 wins

```

# Answer
> 10 votes
## JavaScript (ES6), ~~36~~ 34 bytes

```
f=(n,x=0)=>n?f(n>>>1,x+n%2-.5):x>0

```

# Answer
> 8 votes
# Mathematica, 22 bytes

Saved one byte thanks to @MartinEnder and @JungHwanMin.

```
#>#2&@@#~DigitCount~2&

```

# Answer
> 8 votes
# Brachylog, 6 bytes

```
ḃọtᵐ>₁

```

Try it online!

### Explanation

```
Example input: 13

ḃ        Base (default: binary): [1,1,0,1]
 ọ       Occurences:             [[1,3],[0,1]]
  tᵐ     Map Tail:               [3,1]
    >₁   Strictly decreasing list

```

Since  will never unify its output with a list of digits with leading zeroes, we know that the occurences of `1` will always be first and the occurences of `0` will always be second after .

# Answer
> 7 votes
# Python 3,  ~~44~~  (thanks @c-mcavoy) 40 bytes

```
lambda n:bin(n).count('0')<len(bin(n))/2

```

Try it online!

# Answer
> 7 votes
# Regex (ECMAScript), 183 bytes

This was another interesting problem to solve with ECMA regex. The "obvious" way to handle this is to count the number of `1` bits and compare that to the total number of bits. But you can't directly count things in ECMAScript regex – the lack of persistent backreferences means that only one number may be modified in a loop, and at each step it can only be decreased.

This unary algorithm works as follows:

1. Take the square root of the largest power of 2 that fits into N, and take note of whether the square root was perfect or had to be rounded down. This will be used later.
2. In a loop, move each most-significant `1` bit to the least-significant position where there is a `0` bit. Each of these steps is a subtraction. At the end of the loop, the remaining number (as it would be represented in binary) is a string of `1`s with no `0`s. These operations are actually done in unary; it's only conceptually that they are being done in binary.
3. Compare this "binary string of `1`s" against the square root obtained earlier. If the square root had to be rounded down, use a doubled version of it. This ensures that the "binary string of `1`s" is required to have more than half as many binary digits as N in order for there to be a final match.

To obtain the square root, a variant of the multiplication algorithm briefly described in my Rocco numbers regex post is used. To identify the least-significant `0` bit, the division algorithm briefly described in my factorial numbers regex post is used. These are **spoilers**. So **do not read any further if you don't want some advanced unary regex magic spoiled for you**. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in the list of consecutively spoiler-tagged recommended problems in this earlier post, and trying to come up with the mathematical insights independently.

With no further ado, the regex:

`^(?=.*?(?!(x(xx)+)\1*$)(x)*?(x(x*))(?=(\4*)\5+$)\4*$\6)(?=(((?=(x(x+)(?=\10$))*(x*))(?!.*$\11)(?=(x*)(?=(x\12)*$)(?=\11+$)\11\12+$)(?=.*?(?!(x(xx)+)\14*$)\13(x*))\16)*))\7\4(.*$\3|\4)`

Try it online!

```
# For the purposes of these comments, the input number = N.
^
# Take the floor square root of N
(?=
    .*?
    (?!(x(xx)+)\1*$)    # tail = the largest power of 2 less than tail
    (x)*?               # \3 = nonzero if we will need to round this square root
                        #      up to the next power of two
    (x(x*))             # \4 = potential square root; \5 = \4 - 1
    (?=
        (\4*)\5+$       # Iff \4*\4 == our number, then the first match here must result in \6==0
    )
    \4*$\6              # Test for divisibility by \4 and for \6==0 simultaneously
)
# Move all binary bits to be as least-significant as possible, e.g. 11001001 -> 1111
(?=
    (                                 # \7 = tool for making tail = the result of this move
        (
            (?=
                (x(x+)(?=\10$))*(x*)  # \11 = {divisor for getting the least-significant 0 bit}-1
            )
            (?!.*$\11)                # Exit the loop when \11==0
            (?=
                (x*)                  # \12 = floor((tail+1) / (\11+1)) - 1
                (?=(x\12)*$)          # \13 = \12+1
                (?=\11+$)
                \11\12+$
            )
            (?=
                .*?
                (?!(x(xx)+)\14*$)     # tail = the largest power of 2 less than tail
                \13                   # tail -= \13
                (x*)                  # \16 = tool to move the most-significant 1 bit to the
                                      # least-significant 0 bit available spot for it
            )
            \16
        )*
    )
)
\7                  # tail = the result of the move
\4                  # Assert that \4 is less than or equal to the result of the move
(
    .*$\3
|
    \4              # Double the value of \4 to compare against if \3 is non-empty,
                    # i.e. if we had an even number of total digits.
)

```

# Answer
> 6 votes
# C (gcc), ~~51~~ ~~48~~ ~~41~~ 40 bytes

```
i;f(n){for(i=0;n;n/=2)i+=n%2*2-1;n=i>0;}

```

Try it online!

# Answer
> 6 votes
# x86\_64 machine code, ~~23~~ ~~22~~ 21 bytes

```
31 c0 89 fa 83 e2 01 8d 44 50 ff d1 ef 75 f3 f7 d8 c1 e8 1f c3

```

## Disassembled:

```
  # zero out eax
  xor  %eax, %eax
Loop:
  # copy input to edx
  mov  %edi, %edx
  # extract LSB(edx)
  and  $0x1, %edx
  # increment(1)/decrement(0) eax depending on that bit
  lea -1(%rax,%rdx,2), %eax
  # input >>= 1
  shr  %edi
  # if input != 0: repeat from Loop
  jnz  Loop

  # now `eax < 0` iff the input was not binary heavy,
  neg %eax
  # now `eax < 0` iff the input was binary heavy (which means the MSB is `1`)
  # set return value to MSB(eax)
  shr  $31, %eax
  ret

```

Thanks @Ruslan, @PeterCordes for `-1` byte!

Try it online!

# Answer
> 6 votes
# , ~~54~~ ~~53~~ 51 bytes

*-1 byte thanks to Max Lawnboy*

```
n=scan();d=floor(log2(n))+1;sum(n%/%2^(0:d)%%2)*2>d

```

reads from stdin; returns `TRUE` for binary heavy numbers. `d` is the number of binary digits; `sum(n%/%2^(0:d)%%2` computes the digit sum (i.e., number of ones).

Try it online!

# Answer
> 6 votes
# Kotlin, 50 bytes

```
{i:Int->i.toString(2).run{count{it>'0'}>length/2}}

```

Lambda of implicit type `(Int) -> Boolean`. Version 1.1 and higher only due to usage of `Int.toString(radix: Int)`.

Unfortunately TIO's Kotlin runtime seems to be 1.0.x, so here's a sad dog instead of a TIO link:

# Answer
> 6 votes
## Regex (ECMAScript), ~~85~~ ~~73~~ 71 bytes

```
^((?=(x*?)\2(\2{4})+$|(x*?)(\4\4xx)*$)(\2\4|(x*)\5\7\7(?=\4\7$\2)\B))*$

```

Try it online!

*explanation by Deadcode*

The earlier 73 byte version is explained below.

`^((?=(x*?)\2(\2{4})+$)\2|(?=(x*?)(\4\4xx)*$)(\4|\5(x*)\7\7(?=\4\7$)\B))+$`

Because of the limitations of ECMAScript regex, an effective tactic is often to transform the number one step at a time while keeping the required property invariant at every step. For example, to test for a perfect square or a power of 2, reduce the number in size while keeping it a square or power of 2 (respectively) at every step.

Here is what this solution does at every step:

If the rightmost bit is not a `1`, the rightmost `1` bit (if it is not the only `1` bit, i.e. if the current number is not a power of 2) is moved one step to the right, effectively changing a `10` to a `01` (for example, 1101**1**000 → 11010**1**00 → 110100**1**0 → 1101000**1**), which has no effect on the number's binary-heaviness. Otherwise, the rightmost `01` is deleted (for example 101110**01** → 101110, or 110**01**11 → 11011). This also has no effect on the number's heaviness, because the truth or falsehood of \\$ones\>zeroes\\$ will not change if \\$1\\$ is subtracted from both; that is to say,

\\$ones\>zeroes⇔ones-1\>zeroes-1\\$

When these repeated steps can go no further, the end result will either be a contiguous string of `1` bits, which is heavy, and indicates that the original number was also heavy, or a power of 2, indicating that the original number was not heavy.

And of course, although these steps are described above in terms of typographic manipulations on the binary representation of the number, they're actually implemented as unary arithmetic.

```
# For these comments, N = the number to the right of the "cursor", a.k.a. "tail",
# and "rightmost" refers to the big-endian binary representation of N.
^
(                          # if N is even and not a power of 2:
    (?=(x*?)\2(\2{4})+$)   # \2 = smallest divisor of N/2 such that the quotient is
                           # odd and greater than 1; as such, it is guaranteed to be
                           # the largest power of 2 that divides N/2, iff N is not
                           # itself a power of 2 (using "+" instead of "*" is what
                           # prevents a match if N is a power of 2).
    \2                     # N = N - \2. This changes the rightmost "10" to a "01".
|                          # else (N is odd or a power of 2)
    (?=(x*?)(\4\4xx)*$)    # \4+1 = smallest divisor of N+1 such that the quotient is
                           # odd; as such, \4+1 is guaranteed to be the largest power
                           # of 2 that divides N+1. So, iff N is even, \4 will be 0.
                           # Another way of saying this: \4 = the string of
                           # contiguous 1 bits from the rightmost part of N.
                           # \5 = (\4+1) * 2 iff N+1 is not a power of 2, else
                           # \5 = unset (NPCG) (iff N+1 is a power of 2), but since
                           #   N==\4 iff this is the case, the loop will exit
                           #   immediately anyway, so an unset \5 will never be used.
    (
        \4                 # N = N - \4. If N==\4 before this, it was all 1 bits and
                           # therefore heavy, so the loop will exit and match. This
                           # would work as "\4$", and leaving out the "$" is a golf
                           # optimization. It still works without the "$" because if
                           # N is no longer heavy after having \4 subtracted from it,
                           # this will eventually result in a non-match which will
                           # then backtrack to a point where N was still heavy, at
                           # which point the following alternative will be tried.
    |
        # N = (N + \4 - 2) / 4. This removes the rightmost "01". As such, it removes
        # an equal number of 0 bits and 1 bits (one of each) and the heaviness of N
        # is invariant before and after. This fails to match if N is a power of 2,
        # and in fact causes the loop to reach a dead end in that case.
        \5                 # N = N - (\4+1)*2
        (x*)\7\7(?=\4\7$)  # N = (N - \4) / 4 + \4
        \B                 # Assert N > 0 (this would be the same as asserting N > 2
                           # before the above N = (N + \4 - 2) / 4 operation).
    )
)+
$       # This can only be a match if the loop was exited due to N==\4.

```

# Answer
> 5 votes
# Perl 6,  ~~32~~  30 bytes

```
{[>] .base(2).comb.Bag{qw<1 0>}}

```

Test it

```
{[>] .polymod(2 xx*).Bag{1,0}}

```

Test it

## Expanded:

```
{      # bare block lambda with implicit parameter ｢$_｣

  [>]  # reduce the following with &infix:« > »

    .polymod(2 xx *) # turn into base 2 (reversed) (implicit method call on ｢$_｣)
    .Bag\            # put into a weighted Set
    { 1, 0 }         # key into that with 1 and 0
                     # (returns 2 element list that [>] will reduce)
}

```

# Answer
> 5 votes
## Haskell, ~~41~~ 34

```
g 0=0
g n=g(div n 2)+(-1)^n
(<0).g

```

If `n` is odd, take a `-1` if it's even, take a `1`. Add a recursive call with `n/2` and stop if `n = 0`. If the result is less than `0` the number is binary-heavy.

Try it online!

Edit: @Ørjan Johansen found some shortcuts and saved 7 bytes. Thanks!

# Answer
> 5 votes
# Wise, ~~40~~ 39 bytes

```
::^?[:::^~-&[-~!-~-~?]!~-?|>]|:[>-?>?]|

```

Try it online!

## Explanation

```
::^?                                      Put a zero on the bottom
    [                                     While
     :::^~-&                              Get the last bit
            [-~!-~-~?]!~-?|               Increment counter if 0 decrement if 1
                           >              Remove the last bit
                            ]|            End while
                              :[>-?>?]|   Get the sign

```

# Answer
> 5 votes
# Retina, ~~37~~ 34 bytes

```
.+
$*
+`(1+)\1
$1@
@1
1
+`.\b.

1+

```

Try it online! Link includes smaller test cases (the larger ones would probably run out of memory). Edit: Saved 3 bytes thanks to @MartinEnder. Explanation: The first stage converts from decimal to unary, and the next two stages convert from unary to binary (this is almost straight out of the unary arithmetic page on the Retina wiki, except that I'm using `@` instead of `0`). The third stage looks for pairs of dissimilar characters, which could be either `@1` or `1@`, and deletes them until none remain. The last stage then checks for remaining 1s.

# Answer
> 5 votes
# , 43 bytes

```
max(which(B<-intToBits(scan())>0))/2<sum(B)

```

Try it online!

```
             intToBits(scan())              # converts to bits
          B<-                 >0            # make logical and assign to B
max(which(                      ))/2        # get the length of the trimmed binary and halve
                                    <sum(B) # test against the sum of bits

```

# Answer
> 5 votes
# Julia, 22 bytes

```
x->2*x<4^count_ones(x)

```

# Answer
> 4 votes
# Pyth, ~~9~~ 7 bytes

```
ehc2S.B

```

Try it here.

-2 thanks to FryAmTheEggman.

# Answer
> 4 votes
# R, ~~39~~ 37 bytes

```
sum(intToBits(x<-scan())>0)>2+log2(x)

```

This is a combination of the methods used by @MickyT and @Giuseppe, saving another few bytes.

`sum(intToBits(x) > 0)` counts the amount of `1` bits, and `2+log2(x)/2` is half of the total amount of bits, when rounded down. We don't have to round down because of the behaviour when the two values are equal.

# Answer
> 4 votes
# C# (.NET Core), ~~62~~, 49 bytes

Without LINQ.

EDIT: dana with a -13 byte golf changing the while to a recursive for and returning a bool instead of integer.

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

```

Try it online!

# Answer
> 3 votes
# Jelly, 6 bytes

```
Bµċ0<S

```

Try it online!

# Answer
> 3 votes
# Rust, 30 bytes

```
|x:u64|x<1<<2*x.count_ones()-1

```

Try it online!

# Answer
> 3 votes
# , 12 bytes

```
(+/>-:@#)@#:

```

J executes verbs right-to-left, so let's start at the end and work our way towards the beginning.

**Explanation**

```
         #:       NB. Convert input to list of bits
       -:@#       NB. Half (-:) the (@) length (#)
          >       NB. Greater than
         +/       NB. Sum (really plus (+) reduce (/)

```

# Answer
> 3 votes
# 05AB1E, 4 bytes

Returns 1 if binary heavy, 0 otherwise

```
b.MW

```

Try it online!

```
b            Convert to binary
 .M          Push a list of most frequent chars (contains 0 and 1 in case of a tie)
   W         Push the lowest value from the list
             Implicit output

```

# Answer
> 3 votes
# Vyxal, 4 bytes

```
bĊ↑h

```

Try it Online!

### Explained

```
bĊ↑h
b    # binary
 Ċ↑h # most values outputted, if tie then 0

```

# Answer
> 2 votes
# PHP, 44 bytes

```
for(;$a=&$argn;$a>>=1)$r+=$a&1?:-1;echo$r>0;

```

Try it online!

# PHP, 48 bytes

```
<?=($c=count_chars(decbin($argn)))[49]-$c[48]>0;

```

Try it online!

# Answer
> 2 votes
# Octave, 26 bytes

```
@(a)sum(2*dec2bin(a)-97)>0

```

Try it online!

# Answer
> 2 votes
# Python 2, 44 bytes

```
f=lambda n,c=0:f(n/2,c+n%2*2-1)if n else c>0

```

Try it online!

### Old Answer, 47 bytes

```
c,n=0,input()
while n:c+=n%2*2-1;n/=2
print c>0

```

This is simply a port of @cleblanc's C answer. It's longer than other Python answers but I figured it was worth posting since it's a completely different method of finding the answer.

Try it online!

# Answer
> 2 votes
# C#, 82 bytes

```
n=>{var s=System.Convert.ToString(n,2);return s.Replace("0","").Length>s.Length/2}

```

# Answer
> 2 votes
# Japt, 9 bytes

```
0<¢¬x®r0J

```

Try it online!

## Explanation:

```
0<¢¬x®r0J
  ¢        // Binary; Base-2 of the input
   ¬       // Split into an array
     ®     // Map; At each item:
      r0J  //   Replace 0 with -1
    x      // Sum;
0<         // If the result is greater-than 0, return true; Else, false;

```

# Answer
> 2 votes
# Common Lisp, ~~49~~ 48 bytes

```
(lambda(x)(>(logcount x)(/(integer-length x)2)))

```

Try it online!

*-1 byte thanks to ceilingcat!*

Only two builtin functions (and two operators), but with the long names typical of Common Lisp! At least conceptually very simple.

# Answer
> 2 votes
# Excel, 88 bytes

Un-golfed answer that only handles values up to 511.

```
=SUMPRODUCT(--MID(DEC2BIN(A1),ROW(OFFSET(A$1,,,LEN(DEC2BIN(A1)))),1))>LEN(DEC2BIN(A1))/2

```

### Excel & CSV, 75 bytes.

Save as CSV, and insert Input before first comma:

```
,=DEC2BIN(A1),=SUMPRODUCT(--MID(B1,ROW(OFFSET(A$1,,,LEN(B1))),1))>LEN(B1)/2

```

# Answer
> 2 votes
# , ~~74~~ 62 bytes

```
x=scan();n=strtoi(intToBits(x)[0:log2(x)+1]);2*sum(n)>sum(n|T)

```

**Edit:**

Thanks *Giuseppe*! -12 bytes

Try it online!

# Answer
> 2 votes
# Ruby, ~~39~~ 32 bytes

```
->n{b=n.digits 2;b.sum>b.size/2}

```

Attempt This Online!

# Answer
> 2 votes
# PowerShell, 72 bytes

```
([convert]::ToString("$args",2)-replace'1','+1'-replace'0','-1'|iex)-gt0

```

Try it online!

Converts to Base 2, changes `100` to `+1-1-1` and eval, checks if the result ends up `>0`.

# Answer
> 2 votes
# TIS-100, 432 Bytes

105502 Cycles, 6 Nodes, 46 Instructions

```
@1
MOV RIGHT NIL
MOV UP DOWN
@2
MOV DOWN LEFT
@5
S:MOV ANY ACC
L:SUB 2
SWP
ADD 1
SWP
JGZ L
JLZ B
MOV 0 DOWN
A:MOV 0 ACC
SWP
SUB DOWN
MOV ACC RIGHT
JMP S
B:MOV 1 DOWN
JMP A
@6
MOV 0 UP
L:MOV LEFT ACC
SUB 1
JEZ B
ADD 1
MOV ACC LEFT
MOV 0 DOWN
JMP L
B:MOV 0 UP
MOV 1 DOWN
JMP L
@9
S:MOV UP ACC
MOV ACC UP
JEZ B
MOV 1 RIGHT
JMP S
B:MOV -1 RIGHT
@10
L:SWP
ADD LEFT
SWP
MOV UP ACC
JEZ L
SWP
JGZ B
MOV 0 DOWN
JMP K
B:MOV 1 DOWN
K:MOV 0 ACC

```

EDIT: Explained:

@5 receives any value and divides by two. It passes the remainder down and the quotient right, making sure to correct any errors by subtracting the remainder from @9. @6 receives quotients from @5. If the quotient is 1, it terminates the loop by passing a signal down to print out the answer, then passing a signal to @1 via @2 to read in the next value. Speaking of, @9 and @10 hold the greater than/less than state of 1s and 0s by adding 1 for each 1 and -1 for each 0, then jumping based on the sum.

Play the level by pasting this into the game.

```
function get_name()
    return "BINARY COLLAPSER"
end

function get_description()
    return { "WRITE 1 TO OUT IF THE BINARY REPRESENTATION OF IN CONTAINS MORE ONES THAN ZEROES", "WRITE 0 TO OUT OTHERWISE", "IGNORE LEADING ZEROES"}
end

function get_streams()
    input = {}
    output = {}
    for i = 1,39 do
      x = math.random(1, 999)
        input[i] = x
        ones = 0
        zeroes = 0
        while (x>0) do
            if (x%2 == 1) then
                ones = ones + 1
                x = x - 1
            else
                zeroes = zeroes + 1
            end
            x = x/2
        end
        if (ones > zeroes) then
            output[i] = 1
        else
            output[i] = 0
        end
    end
    return {
        { STREAM_INPUT, "IN.A", 1, input },
        { STREAM_OUTPUT, "OUT.A", 2, output },
    }
end

function get_layout()
    return {
        TILE_COMPUTE,   TILE_COMPUTE, TILE_COMPUTE,     TILE_COMPUTE,
        TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,
        TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,
    }
end

```

# Answer
> 2 votes
# Java (OpenJDK 8), 43 bytes

```
n->n.bitCount(n)>n.toString(n,2).length()/2

```

Try it online!

# Java (OpenJDK 8), 31 bytes using BigInteger

I suspect this would need to count the import for 28 more bytes though.

```
n->n.bitCount()>n.bitLength()/2

```

Try it online!

# Answer
> 2 votes
# q/kdb+, ~~34~~ ~~33~~ 28 bytes

**Solution:**

```
sum[b]>.5*(#)*:[b&:]_b:2 vs

```

**Examples:**

```
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 1
1b
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 2
0b
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 4
0b
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 5
1b
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 60
1b
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 316
1b
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 632
0b
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 2147483647
1b
q)sum[b]>.5*(#)*:[b&:]_b:2 vs 2147483648
0b

```

**Explanation:**

Convert input to binary, chop off leading zeroes, compare whether there are more ones (`sum[b]`) than half the length of the list (`0.5 * count...`).

```
sum[b] > 0.5 * count first[where b] _ b:2 vs / ungolfed solution
                                        2 vs / convert right to base 2
                                      b:     / save in variable b for use later
                           where b           / indexes where b is true
                     first[       ]          / perform first on the stuff in brackets
                                    _        / drop, drops left items from right, basically drop all leading 0s
               count                         / returns length of this list
         0.5 *                               / half this value
       >                                     / greater-than, returns true or false
sum[b]                                       / how many 1s there are in b

```

**Notes:**

Golfing was simply replacing the q keywords with their k equivalents

# Answer
> 2 votes
# k, 22 bytes

```
{.5<avg X@&:|\X:0b\:x}

```

`q` translation:

```
{.5 < avg X where maxs X:0b vs x}

```

Interpreter available here

# Answer
> 2 votes
# Python, 33 bytes

```
lambda x:2*x<4**bin(x).count('1')

```

Try it online!

# Answer
> 2 votes
# tinylisp, 93 bytes

```
(d _(q((N R D)(i(l N 2)(i R(_ R 0(a(s(s 1 N)N)D))(l D 1))(_(s N 2)(a R 1)D
(d H(q((N)(_ N 0 0

```

This was fun. I went through a few different ideas before I was able to beat my initial 105-byte solution that used library functions.

Try it online!

### Ungolfed + explanation

```
(load library)

(def _binary-heavy
 (lambda (num rest diff)
  (if (less? num 2)
   (if rest
    (_binary-heavy rest 0 (+ diff (if num (neg 1) 1)))
    (less? diff 1))
   (_binary-heavy (- num 2) (inc rest) diff))))

(def binary-heavy (lambda (num) (_binary-heavy num 0 0)))

```

There are no division or modulo builtins in tinylisp, so we use an algorithm that only does addition and subtraction.

The helper function `_binary-heavy` has three arguments:

* `num` starts out as the integer we're analyzing
* `rest` ends up as half of `num`, and then becomes the new `num` in a recursive call
* `diff` stores the difference between the number of 0 bits and the number of 1 bits we've seen so far

The function recurses in a couple of different ways:

* If `num` is 2 or greater, subtract 2 from `num`, add 1 to `rest`, and recurse.
* If `num` is 0 or 1, then `rest` now contains the original `num` divided by 2, and `num` contains the original `num` mod 2. In other words, `num` is the least significant bit, and `rest` is the rest of the number. Here we have two possibilities:
    + If `rest` is not zero, there are more bits to process, so we update `diff` and recurse with `rest` as the new `num`. Since `diff` is (number of 0 bits) minus (number of 1 bits), we want to add 1 if `num` is 0 and -1 if `num` is 1. The golfed code accomplishes this by adding `(s(s 1 N)N)`--in infix, `1 - 2*num`.
    + If `rest` is zero, we're done and just need to return a result. Note that `num` now holds the most significant bit, which is always 1. So the final diff is `diff - 1`, and we want to check whether this is less than 0. But `diff - 1 < 0` is the same as `diff < 1`, which is what we return.

Finally, we define our main function, `binary-heavy`, to take one argument `num` and pass it on to the helper function, with `rest` and `diff` initially 0.

# Answer
> 2 votes
# Ruby, ~~30~~ 27 bytes

```
->n{n<4**n.digits(2).sum/2}

```

Try it online!

# Answer
> 2 votes
# Alchemist, 122 bytes

```
_->In_a
n+a+0z->n+z
a+z->b
n+0a->d
0n+z->2c
0n+0z+b->a
0n+0z+0b+a->a+n
c+d->
0z+0a+0b+0_+0f->s+f
0c+s->Out_c
0d+c+s->Out_f

```

Try it online!

Test cases

Outputs 0 for false and 1 for true.

# Answer
> 2 votes
# APL (Dyalog Unicode), 14 bytes

-6 thanks to @Razetime -1 thanks to @rak1507

```
f←(≢<2×+/)2∘⊥⍣¯1

```

explanation:

```
(≢<2×+/)2∘⊥⍣¯1
        2∘⊥⍣¯1     ⍝ convert the number to a binary vector inverting decode (⊥)
   2×+/            ⍝ doubled count of ones in the binary representation
 ≢                 ⍝ amount of bits in the binary representation
  <                ⍝ is it smaller?

```

Try it online!

original solution:

```
(+/∘~<+/)2∘⊥⍣¯1

```

explanation:

```
(+/∘~<+/)2∘⊥⍣¯1
         2∘⊥⍣¯1     ⍝ convert the number to a binary vector inverting decode (⊥)
      +/            ⍝ count of ones in the binary representation
    ~               ⍝ negate the number
 +/∘                ⍝ count ones in the negated number, effectively counting zeros
     <              ⍝ is the amount of zeros smaller than the amount of ones?

```

# Answer
> 2 votes
# Factor, ~~35~~ 13 bytes

```
[ >bin mode ]

```

Try it online!

Outputs `49` for truthy and `48` for falsey.

* `>bin` Convert input integer to binary string
* `mode` Return the character that occurs most often (ties return 48)

# Answer
> 2 votes
# Arturo, 36 bytes

```
$=>[<size d--1∑d:<=digits.base:2&]

```

Try it

# Answer
> 2 votes
# Uiua, ~~12~~ ~~11~~ 8 bytes

```
<×2⊃/+⧻⋯

```

Try it!

```
<×2⊃/+⧻⋯
       ⋯  # convert number to bit array
      ⧻   # length
    /+    # sum
   ⊃      # fork (do sum and length on the same value)
 ×2       # double
<         # less than

```

# Answer
> 1 votes
# 05AB1E, ~~8~~ 6 bytes

-2 bytes thanks to Erik the Outgolfer

```
b1Ý¢`‹

```

Try it online! or Try all tests

# Answer
> 1 votes
# Pari/GP, 27 bytes

```
n->2*vecsum(b=binary(n))>#b

```

Try it online!

# Answer
> 1 votes
# GolfScript, 15 bytes

```
~2base.0-,\1-,>

```

Try it online!

# Answer
> 1 votes
# Stacked, 17 bytes

```
[bits tmo sum 0>]

```

Try it online!

This is a pretty simple answer. Takes the `bits` of the top number, perofrms `2n-1` (`tmo`), calculates their `sum`, and checks if it is `>` than `0`.

# Answer
> 1 votes
## TI-Basic, 29 bytes

```
:Prompt N
:While int(N
:.5int(N→N
:P-1+4fPart(N→P
:End
:P>0

```

# Answer
> 1 votes
# CJam, 10 bytes

```
qi2b$_:!$>

```

Try it online

```
qi2b   e# convert input to base 2 as an array (43 => [1,0,1,0,1,1,])
$      e# sort array ([0,0,1,1,1,1])
_:!    e# make copy of array and invert truth value of each element ([1,1,0,0,0,0])
$      e# sort copy ([0,0,0,0,1,1])
>      e# if first array is lexicographically greater than copy, return true (only happens if 1st array had more ones than zeroes).

```

# Answer
> 1 votes
## Sed, 218 bytes (91 with unary input)

```
:u
s/\b9/;8/
s/\b8/;7/
s/\b7/;6/
s/\b6/;5/
s/\b5/;4/
s/\b4/;3/
s/\b3/;2/
s/\b2/;1/
s/\b1/;0/
s/\b0//
/[^;]/s/;/&&&&&&&&&&/g
tu
s/$/x/
:a
s/;;/,/g
s/,x/,x0/
s/;x/x1/
y/,/;/
s/10//
s/01//
ta
s/x$/0/
s/\(.\)\1/\1/g
s/x//

```

Outputs 1 for truthy and 0 for falsey.

Decimal to unary conversion from this answer.

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
b{γ€g¥

```

Try it online!

Results:

* 0 or higher means a non-heavy number.
* Negative numbers represent the binary-heavy numbers.

# Answer
> 1 votes
# Pyt, 4 bytes

```
←ɓąṀ

```

Explanation:

```
←             Get input
 ɓ            Get binary representation as string
  ą           Convert to array of digits
   Ṁ          Get the mode of the array (this returns the smallest if there are multiple)

```

# Answer
> 1 votes
# Attache, 13 bytes

```
{1~_>0~_}@Bin

```

Try it online!

## Explanation

```
{1~_>0~_}@Bin
          Bin    convert the input to binary
{       }@       _ = binary input
 1~_             count of 1s in input
    >            is greater than?
     0~_         the count of 0s in the input

```

## Alternatives

**17 bytes:** `Min@Commonest@Bin`

**17 bytes:** `/N@@Commonest@Bin`

**18 bytes:** `{Sum@_/#_>0.5}@Bin`

**18 bytes:** `/Id@@Commonest@Bin`

**18 bytes:** `Last@Commonest@Bin`

**19 bytes:** `{_>0.5}@Average@Bin`

**22 bytes:** `0&`<@Sum##{2*_-1}=>Bin`

**23 bytes:** ``<@@{Sum@`=&_=>0'1}@Bin`

**23 bytes:** `{&`<!Sum@`=&_=>0'1}@Bin`

**30 bytes:** `{&`<!Sum=>Table[`=,0'1,_]}@Bin`

# Answer
> 1 votes
# Red, 74 bytes

```
func[n][(sum b: collect[until[keep n % 2 1 > n: n / 2]])>((length? b)/ 2)]

```

Try it online!

# Answer
> 1 votes
# Forth (gforth), 56 bytes

```
: f 0 swap begin 2 /mod >r 2* 1- + r> ?dup 0= until 0> ;

```

Try it online!

### Explanation

Loop through the binary digits of the number and add 1 to a counter if the digit is 1, and subtract 1 if the digit is 0. If the total is greater than 0 there are more 1's than 0's.

### Code Explanation

```
: f            \ start new word definition
  0 swap       \ add a counter and move it below the input number on the stack
  begin        \ start an uncounted loop
    2 /mod     \ get the quotient and remainder of dividing by 2 (get binary digit and rest of number)
    >r         \ stick the remaining number on the return stack
    2* 1- +    \ convert remainder to 1 or -1 and add to counter
    r>         \ remove remaining number from the return stack
    ?dup       \ duplicate if not equal to 0
  0= until     \ end the loop if the remaining number is 0
  0>           \ return true if counter is greater than 0
;              end word definition

```

# Answer
> 1 votes
# C, 49 bytes

```
f(n){int a=0;for(;n;n/=2)a+=n%2?1:-1;return a>0;}

```

Possible too much long for you...

# Answer
> 1 votes
# Stax, 4 bytes

```
:B:M

```

Run and debug it

`:B` gets the binary digits of the input. `:M` gets the mode. In the case of a tie, it will be the last element to appear (always 0).

# Answer
> 1 votes
# K (ngn/k), ~~17~~ ~~13~~ 10 bytes

-4 bytes by changing approach

-3 bytes by making code tacit (thanks @ngn)

```
0>+/1-2*2\

```

Try it online!

* `2\x` convert input to base-2; this already trims any leading 0's
* `1-2*` convert 1's to -1's and 0's to 1's
* `0>+/` is the sum less than 0?

# Answer
> 1 votes
## ARM Thumb-2 (alternative), 16 bytes

Alternative approach which mirrors this x86 answer although it is just as small to maintain the bool return value.

Since we need to mov the result to r0 anyways, we can invert the operation and use that opcode to return the sign bit.

Raw machine code:

```
2100 0840 bf2c 3901 3101 d1fa 0fc8 4770

```

Uncommented Assembly:

```
        .syntax unified
        .arch armv6t2
        .globl binary_heavy
        .thumb
        .thumb_func
binary_heavy:
        movs    r1, #0
.Lloop:
        lsrs    r0, r0, #1
        ite     cs
        subcs   r1, #1
        addcc   r1, #1
        bne     .Lloop
.Lloop_end:
        lsrs    r0, r1, #31
        bx      lr

```

The explanation is the same as the original one, but instead of adding to two different variables, we are adding and subtracting from the same variable, and returning the sign bit by doing a logical right shift by 31.

## ARM Thumb-2 (previous approach), 22 20 bytes

Longer but uses an original idea.

Raw machine code:

```
2101 2200 0840 bf2c 3201 3101 d1fa 428a
4140 4770

```

Uncommented Assembly:

```
        .syntax unified
        .arch armv6t2
        .globl binary_heavy
        .thumb
        .thumb_func
binary_heavy:
        movs    r1, #1
        movs    r2, #0
.Lloop:
        lsrs    r0, r0, #1
        ite     cs
        addcs   r2, #1
        addcc   r1, #1
        bne     .Lloop
.Lloop_end:
        cmp     r2, r1
        adcs    r0, r0
        bx      lr

```

## Explanation

> We are about to do some wonky stuff with the condition codes, so you might want to look at the condition code table in this article if you aren't familiar with them.

C signature:

```
bool binary_heavy(uint32_t val);

```

First, set up r1 to count the zeros and r2 to count the ones.

*Wait, why do we start with zeros = 1?* You'll see.

```
binary_heavy:
        movs    r1, #1
        movs    r2, #0

```

Then, begin our loop. All the logic can be handled by how `lsrs` updates the flags.

`lsrs` does a logical right shift, stores the last bit shifted in the carry flag, and sets the zero and negative flags based on the result.

So we can basically do this logic using nothing but `lsrs` and some flag checking:

```
do {
    if (val & 1) {
        ++ones;
    } else {
        ++zeros;
    }
} while (val >>= 1);

```

```
.Lloop:
        lsrs    r0, r0, #1

```

First, we do an IT block to add to either the ones count or the zeroes count.

```
        ite     cs
        addcs   r2, #1
        addcc   r1, #1

```

Thankfully, since most narrow instructions do not set flags in IT blocks, we can also use the same `lsrs` flags to check if the value is still non-zero and loop.

```
        bne     .Lloop

```

Here is why we set the zeros counter to `1`.

We can do a shortcut if we can turn the condition into a greater than or equal. However, if the ones and zeros are equal, it is considered not binary heavy. That is why we need to start the zeros with `1`, because we can offset it.

The shortcut? You guessed it, an add with carry!

* We know that `r0` is zero since if it wasn't, we'd be looping now.
    + That means that `r0` will be `0 + 0 + carry`.
* Greater than or equal means the carry flag is set
    + Therefore, the carry flag being set means greater than or equal.
* Since we modified the zeros initial value, greater than or equal means that the number is binary heavy.
    + Which means the carry flag is set if the number is binary heavy.

So we are essentially setting `r0` to the carry flag, making it act as a boolean....and our return value.

```
.Lloop_end:
        cmp     r2, r1
        adcs    r0, r0

```

Return.

```
        bx    lr

```

# Answer
> 1 votes
# J-uby, ~~49~~ 32 bytes

Based on G B’s Ruby answer.

```
:<%(~:digits&2|:sum|:**&4|~:/&2)

```

Attempt This Online!

# Answer
> 1 votes
# Husk, 4 bytes

```
>.Aḋ

```

Try it online!

```
>.Aḋ
  A   # The average
   ḋ  # of the binary digits
>     # is greater than
 .    # 0.5

```

# Answer
> 1 votes
# K (ngn/k), 19 bytes

```
{n:2\x;(#n^1)<#n^0}

```

Try it online!

This is the first time where using a variable saves more bytes than just duplicate. It's also much simpler than I thought. Return `1` for true, and `0` for false.

Explanation:

```
{n:2\x;(#n^1)<#n^0}    Main function. Takes x as input
 n:                    Assign variable n to
   2\x;                x converted to base 2, return back a binary array
       (#   )          Length of
         n^1           n without 1 in its array
             <         Less than
              #        Length of
               n^0     n without 0 in its array

```

# Answer
> 1 votes
# ///, 156 bytes

```
/9/8*//8/7*//7/6*//6/5*//5/4*//4/3*//3/2*//2/1*//1/0*//*0/9*//0///*/>oi//i>/i//io/oi//oii/i\o//oi/_i//_///>o/>//>///i\o///o\i///|i/T//Ti/T//|o/F//Fo/F//|/F/

```

Try it online!

The input is `|n` where n is a number.

## Explanation:

```
/9/8*//8/7*//7/6*//6/5*//5/4*//4/3*//3/2*//2/1*//1/0*//*0/9*//0//

```

Convert from Base 10 (decimal) to unary (Taken from the wiki)

```
/*/>oi//i>/i//io/oi//oii/i\o//oi/_i//_///>o/>//>//

```

Convert from unary to binary (`i` and `o`) (Also, taken from the wiki)

```
/i\o///o\i//

```

Replace `io` to empty string as many times, then repeat but `oi` to empty string

```
/|i/T//Ti/T/

```

If the new string has `i`, Replace to `T`

```
/|o/F//Fo/F/

```

Else, if the new string has `o`, Replace to `F`

```
/|/F/

```

Else replace to `F`

And output the new string.

# Answer
> 1 votes
# Jelly, 4 bytes

```
BÆṃP

```

Try it online!

Nothing clever here :P

```
   P    Take the product of
 Æṃ     the most common
B       binary digits.

```

# Answer
> 1 votes
# Thunno, \\$8\log\_{256}(96)\approx\\$ 6.58 bytes

```
bD1cs0c>

```

Attempt This Online!

#### Explanation

```
   # Implicit input
bD # Binary, duplicate
1c # Count of 1s
s  # Swap
0c # Count of 0s
>  # Greater than?
   # Implicit output

```

# Answer
> 1 votes
# JavaScript (Node.js), 44 ~~47~~ bytes

> -3 bytes thanks to *l4m2* tip and some other improvements

Different approach but can't beat the recursive JS answers.

```
l=>[...l.toString(a=2)].map(e=>a+=e-.5)&&a>2

```

Try it online!

The algorithm is pretty straightforward.
We convert the decimal into binary, and then we parse each bit while maintaining a score. For each `1` we increase the score by `0.5`, and for each `0` we decrease it by `0.5`.
At the end we check if the score is greater than `2` (because it was shorter that way for the declaration of variable `a`)

# Answer
> 1 votes
# Turing Machine Code, 332 bytes

Terminates in state `halt` for truthy, or `halt-r` for falsey.

```
0 * * r 0
0 _ _ l 1
1 0 9 l 1
1 9 8 l 2
1 8 7 l 2
1 7 6 l 2
1 6 5 l 2
1 5 4 l 2
1 4 3 l 2
1 3 2 l 2
1 2 1 l 2
1 1 0 l 2
1 _ _ l A
2 _ _ l 3
2 * * l 2
3 1 0 l 3
3 * 1 r 4
4 * * r 4
4 _ _ r 0
A * * l A
A 1 & l B
A 0 & l C
A & & l A
B 0 & r D
B * * l B
C 1 & r D
C * * l C
D * * r D
D _ _ l A
B _ _ * halt
C _ _ * halt-r
A _ _ * halt-r

```

Try it online: http://morphett.info/turing/turing.html?ad9fead44f5ee4db3ee96c4b6c9d3f0b

# Answer
> 1 votes
# Go, 101 bytes

```
import(."strconv";."strings")
func f(n int64)bool{x:=FormatInt(n,2)
return Count(x,"1")>Count(x,"0")}

```

Attempt This Online!

#### Commented

```
import (."strconv"; ."strings")        // Boilerplate
func f(n int64) bool {                 // Boilerplate
x := FormatInt(n, 2)                   // Convert n to binary
return Count(x, "1") > Count(x, "0")}  // Is the count of 1s more than the count of 0s?

```

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
ḃk#cẸ<

```

Attempt This Online!

#### Explanation

```
ḃk#cẸ<  # Implicit input           -> n
ḃ       # Binary representation    -> binary
 k#     # Push the pair [0, 1]     -> binary, [0, 1]
   c    # Counts of each           -> [count of 0, count of 1]
    Ẹ   # Dump onto stack          -> count of 0, count of 1
     <  # Less than                -> count of 0 < count of 1
        # Implicit output

```

# Answer
> 1 votes
# Uiua, 7 bytes

```
>∩/+¬.⋯

```

Try it!

```
      ⋯     # encode as bits
    ¬.      # make a copy with bitwise-NOT
 ∩          # for each of these:
  /+        #   sum
>           # is the second bigger than the first?

```

# Answer
> 1 votes
# Fortran (GFortran), 38 bytes body, 13 bytes boilerplate

```
program x

read*,n;print*,2*popcnt(n)>64-leadz(n)

end

```

Try it online: , , , , 60, 316, 632, 2147483647, 2147483648

The code reads a single 64 bit integer `n` from standard input and ouputs `T` for a binary-heavy number or `F` otherwise.

It uses `popcnt()` to count the number of ones and `leadz()` to count the number of leading zeros, both in the binary representation of `n`. The inequality to check is

```
popcnt(n) > (64 - leadz(n) - popcnt(n))

```

which can be written shorter as

```
(2 * popcnt(n)) > (64 - leadz(n))

```

The code needs to be compiled with `-fdefault-integer-8` to enable 64 bit integers as the default.

# Answer
> 0 votes
# CJam, 11 bytes

```
2,ri2bfe=:<

```

Try it online!

# Answer
> 0 votes
# Pyth, 15 bytes

```
<.*uXsHG1.BQ,ZZ

```

Try it online! Probably not the shortest solution out there, but I find it elegant.

**Explanation**

```
         .BQ       # Convert input to a binary string
   u        ,ZZ    # Reduce starting with (0, 0)...
    XsHG1          # ...by adding 1 to the first element of the couple if a 0 is encountered, or to the second element if a 1 is encountered
 .*                # Splat the couple: (x, y) -> x y
<                  # Check that x < y (x being the number of zeros, y the number of ones)

```

# Answer
> 0 votes
# Check, ~~45~~ 41 bytes

```
>\          #v
#:>2%R+r\)\$##?
d$R-)>]*!p

```

Try it online!

This is probably golfable. I don't like the huge space on the first line.

## Explanation

The program starts out with the input number on top of the stack. The IP is in 1D mode.

The `>` pushes a 0 to the stack, and then the `\` swaps it with the input number. The stack now looks like `0, input`, and the register is initialized to 0.

`#v` turns the IP into 2D mode and makes it start moving downwards. The second line is a loop that does this:

* If the current value is 0, end the loop.
* Otherwise, take the current value modulo 2.
* Add that value to the value of the register (which counts the number of ones), and then unconditionally add 1 to the other value on the stack (which counts the total number of digits).
* Int-divide the current value by 2.

Once the loop exits, one value on the stack will contain the number of digits. Divide that by 2. Then, take the value in the register, which counts the total number of ones. If the number of ones is greater than the total number of digits // 2, then the condition is true. However, Check has no built-in for checking whether one number is greater than another, so this is the simplest way:

* Subtract the two values. The condition is now only true when the result is negative.
* Increment the value. The condition is now only true when the result is negative or 0.
* Repeat a singleton array that many times. In Check, trying to repeat an array a negative amount of times yields an empty array, which means that the result will be an empty array if and only if the condition is true.
* The `!p` negates the empty array and prints the result.

# Answer
> 0 votes
## Ohm, 7 bytes

```
bS╞╠l;h

```

### Explanation

```
bS╞╠l;h  Main wire
b        binary representation
 S       sorted
  ╞      grouped
   ╠l;   sorted by length
       h the first element

```

# Answer
> 0 votes
# Swift 3, 101 bytes

```
func h(b:Int)->Any{let a=String(b,radix:2).characters;return a.reduce(0){$1=="1" ?$0+1:$0}>a.count/2}

```

Try it online

# Answer
> 0 votes
# Perl 5, 33 bytes

```
$_=sprintf"%b",<>;say y/1//>y/0//

```

Try it online!

# Answer
> 0 votes
# Japt, ~~9~~ 8 bytes

```
2Æ¤èXÃr<

```

Try it or run all test cases

```
2Æ¤èXÃr<     :Implicit input of integer U
2Æ           :Map each X in the range [0,2)
  ¤          :  Convert U to binary string
   èX        :  Count the occurrences of X
     Ã       :End map
      r<     :Reduce by less than

```

# Answer
> 0 votes
# Add++, 12 bytes

```
L,BBEDdb!Es<

```

Try it online!

# Answer
> 0 votes
# C (gcc), 37 bytes

```
i;f(n){for(;n;n/=2)i+=n%2*8-4;i=i>2;}

```

Idea is that we calculate difference of number of 1s and 0s multiplied by for, so we don't care that i might be 1 after previous invocation.

Try it online!

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 144 bytes

```
 N =INPUT
A O =O REMDR(N,2)
 N =GT(N) N / 2 :S(A)
 K =SIZE(O) - 1
R O 0 ='' :S(R)
 L =SIZE(O)
 OUTPUT =GE(K - L,L) 0 :F(Y)S(END)
Y OUTPUT =1
END

```

Try it online!

# Answer
> 0 votes
# Husk, 7 bytes

```
ΣFż*gOḋ

```

Try it online!

### Explanation

```
ΣFż*gOḋ  -- implicit input N, for example: 5
      ḋ  -- convert N to base 2: [1,0,1]
     O   -- sort: [0,1,1]
    g    -- group equal elements: [[0],[1,1]]
 F       -- reduce by the following (ie. apply function to the two groups*):
  ż*     --   zip with multiplication, but keep trailing elements: [0*1,1] == [0,1]
Σ        -- sum: 1

```

---

***** The special cases where N = 2x-1 (x = 0…) also works because a reduce (`foldl1`) with a singleton list simply returns that element.

# Answer
> 0 votes
# cQuents, 15 bytes

```
:uJ$);1)>uJ$);0

```

Note that it only works on the latest commit, had to fix a bug, so TIO may or may not work depending on when you read this.

Try it online!

# Explanation

```
:uJ$);1)>uJ$);0

:                    Mode: sequence 1, given input n, output nth term in sequence
                     Each term in the sequence equals:
 u   ;1)             Count number of ones in
  J$)                                        binary representation of current index
        >            Greater than (returns 1 (truthy) if true and 0 (falsey) if false)
         u   ;0)     Count number of zeroes in           (implicit closing ')')
          J$)                                  binary representation of current index

```

# Answer
> 0 votes
# CPU x86 instruction set, 18 bytes

```
00000750  8B4C2404          mov ecx,[esp+0x4]
00000754  31C0              xor eax,eax
00000756  D1E9              shr ecx,1
00000758  7302              jnc 0x75c
0000075A  40                inc eax
0000075B  40                inc eax
0000075C  48                dec eax
0000075D  85C9              test ecx,ecx
0000075F  75F5              jnz 0x756
00000761  C3                ret

```

it return \>0 if the number is "binary-heavy" else if result is \<=0 it is not "binary-heavy". Code for test it and see how to call it:

```
; nasmw -fobj  this.asm
; bcc32 -v  this.obj

section _DATA use32 public class=DATA

global _main
global _BinHev
extern _printf
fmt db "%u -> %d" , 13, 10, 0, 0

section _TEXT use32 public class=CODE

      align   8
_BinHev:
      mov     ecx,  dword[esp+4]
      xor     eax,  eax
.0:   shr     ecx,  1
      jnc     .1
      inc     eax
      inc     eax
.1:   dec     eax
      test    ecx,  ecx
      jnz     .0
.z:   ret

_main:
      pushad
      mov     ebx,  1
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12
      mov     ebx,  2
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12
      mov     ebx,  4
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12
      mov     ebx,  5
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12
      mov     ebx,  60
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12
      mov     ebx,  316
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12
      mov     ebx,  632
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12
      mov     ebx,  2147483647
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12
      mov     ebx,  2147483648
      push    ebx
      call    _BinHev
      add     esp,  4
      push    eax
      push    ebx
      push    fmt
      call    _printf
      add     esp,  12

      popad
      mov     eax,  0
      ret

```

results:

```
1 -> 1
2 -> 0
4 -> -1
5 -> 1
60 -> 2
316 -> 1
632 -> 0
2147483647 -> 31
2147483648 -> -30

```

# Answer
> 0 votes
# bash 76

**Pure** bash!

```
i=$1;for((r=$[$1&1];i>>=1;)){ r=$[i&1]$r;};i=${#r};s=${r//1};((i>(${#s}*2)))

```

## Demo:

```
isbinheavy() {
    i=$1;for((r=$[$1&1];i>>=1;)){ r=$[i&1]$r;};i=${#r};s=${r//1};((i>(${#s}*2)))
}

for val in 1 2 4 5 60 316 632 2147483647 2147483648 ;do
    if isbinheavy $val; then
        res=True
    else
        res=False
    fi
    printf "%-12s -> %32s -> %s\n" $val $r $res
done

```

Will render:

```
1            ->                                1 -> True
2            ->                               10 -> False
4            ->                              100 -> False
5            ->                              101 -> True
60           ->                           111100 -> True
316          ->                        100111100 -> True
632          ->                       1001111000 -> False
2147483647   ->  1111111111111111111111111111111 -> True
2147483648   -> 10000000000000000000000000000000 -> False

```

## Explanation:

1. Set variable `i` to submited integer
2. Begin `for` loop by
    1. setting variable `r` to low significant bit of `$1`
    2. set *end of loop* on `i` variable, shifting them by 1 bit on each check
3. In loop:
    1. add low significant bit of resulted `$i` on left side of `$r`
4. Then store into variable `i`, length of `$r`
5. Drop all `0` from string `$r` then store string into variable `s`.
6. numerically test if `$i` \> `2 x length of $s`

# Answer
> 0 votes
# C# (.NET Core), 48 bytes

```
bool f(int x,int c=0)=>x<1?c>0:f(x/2,c-1+x%2*2);

```

Try it online!

There were already a few C# solutions, but this is the first recursive one.

An optional counter argument is use to count `0`'s and `1`'s. A `0` will decrement the counter and a `1` will increment it. We are done when no more `1`'s are present, a positive counter indicates there were a greater number of `1`'s than `0`'s.

# Answer
> 0 votes
## MBASIC, 86 bytes

```
1 INPUT N
2 Q=INT(N/2):IF N MOD 2=1 THEN O=O+1 ELSE Z=Z+1
3 N=Q:IF N>0 THEN 2
4 PRINT O>Z

```

Prints -1 for true, 0 for false

Examples:

```
? 316
-1

? 632
 0

```

# Answer
> 0 votes
# C# (.NET Core), 98 bytes

Way too long xD

```
y=>{var b=Convert.ToString(y,2);for(int i=y=0;i<b.Length;)y+=b[i++]=='1'?1:-1;return y>0?1>0:1<0;}

```

Try it online!

# Answer
> 0 votes
# GNU AWK, 55 52 bytes

```
{for(b=0;$1;$1=rshift($1,1))$1%2?b++:b--;print(b>0)}

```

Step by step:

```
{
for(
    b=0;            # at the beginning of each loop, starts over the bit count
    $1;             # loops until input reaches zero
                    # (positive values return true evaluation)
    $1=rshift($1,1) # at the end of each loop, right shift bitwise the input by 1 bit
   )
      $1%2?b++:b--; # if input is even, +1 to the bit count; -1 if odd
print(b>0)          # after the looping, prints the evaluation of b>0; 1 if true, 0 if false
}

```

Try it online!

---
Tags: code-golf, number, decision-problem, binary
---