63
\$\begingroup\$

An integer is binary-heavy if its binary representation contains more 1s than 0s 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

\$\endgroup\$
8
  • \$\begingroup\$ What if my language can't handle the last test case because it's outside the bounds of what's considered a positive integer? \$\endgroup\$ Jul 13 '17 at 14:52
  • 1
    \$\begingroup\$ @musicman523 afaik Standard I/O rules state that you only have to accept numbers representable by your language's number format. Note that "gaming" this by using something like boolfuck is considered a Standard Loophole \$\endgroup\$
    – Mayube
    Jul 13 '17 at 14:53
  • \$\begingroup\$ Does any truthy/falsy value count or do we need two distinct values? \$\endgroup\$ Jul 13 '17 at 15:22
  • \$\begingroup\$ @EriktheOutgolfer any value \$\endgroup\$
    – Mayube
    Jul 13 '17 at 15:35
  • 7
    \$\begingroup\$ Aka A072600, if this helps anybody. \$\endgroup\$
    – dcsohl
    Jul 13 '17 at 17:59

81 Answers 81

1 2
3
0
\$\begingroup\$

CJam, 11 bytes

2,ri2bfe=:<

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ @MartinEnder How does :< work in your example? If it's a quick fold or quick map, I don't really get it. \$\endgroup\$
    – geokavel
    Jul 14 '17 at 2:46
  • \$\begingroup\$ @geokavel I just noticed it doesn't work when the input contains only 0-bits or only 1-bits so nevermind. \$\endgroup\$ Jul 14 '17 at 4:59
  • \$\begingroup\$ @EriktheOutgolfer I suggested sorting, RLE, comparison, but that assumes that both zero and one are present in the number. \$\endgroup\$ Jul 14 '17 at 9:12
  • \$\begingroup\$ @MartinEnder Oh yeah RLE is a big no here. I think you suggested ri2b$e`0f=:< which is longer anyways. \$\endgroup\$ Jul 14 '17 at 9:13
0
\$\begingroup\$

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)
\$\endgroup\$
2
  • \$\begingroup\$ Probably? \$\endgroup\$ Jul 13 '17 at 15:25
  • 3
    \$\begingroup\$ @EriktheOutgolfer At least mine has an explanation. \$\endgroup\$
    – Jim
    Jul 13 '17 at 15:32
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ -11 bytes: func h(b:Int){let a=String(b,radix:2).characters;print(a.filter{$1=="1"}.count>a.count/2)} \$\endgroup\$
    – Herman L
    Dec 12 '17 at 16:53
  • \$\begingroup\$ -22 bytes with Swift 4 func h(b:Int){let a=String(b,radix:2);print(a.filter{$1=="1"}.count>a.count/2)} \$\endgroup\$
    – Herman L
    Dec 12 '17 at 16:58
0
\$\begingroup\$

Perl 5, 33 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Add++, 12 bytes

L,BBEDdb!Es<

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Red, 74 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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...

\$\endgroup\$
7
  • \$\begingroup\$ Could you specify the compiler you used? \$\endgroup\$ Feb 6 '19 at 10:23
  • \$\begingroup\$ Possibly f(n,a){for(a=0;n;n/=2)a+=n%2*2-1;a=a>0;}? \$\endgroup\$ Feb 6 '19 at 10:25
  • \$\begingroup\$ @JonathanFrech each C compiler \$\endgroup\$
    – user58988
    Feb 6 '19 at 12:24
  • \$\begingroup\$ I would think there are a lot of C compilers out there. Do you mean C89 compliant or something along those lines? \$\endgroup\$ Feb 6 '19 at 19:39
  • \$\begingroup\$ Yes C89 standard (I hope at last)... It would be good for me to know some C compiler not compile above code \$\endgroup\$
    – user58988
    Feb 7 '19 at 10:10
0
\$\begingroup\$

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!

\$\endgroup\$
1
0
\$\begingroup\$

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!

\$\endgroup\$
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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