Is the number binary-heavy?

58

3

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

Skidsdev

Posted 2017-07-13T14:26:46.563

Reputation: 9 656

What if my language can't handle the last test case because it's outside the bounds of what's considered a positive integer? – musicman523 – 2017-07-13T14:52:51.130

1@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 – Skidsdev – 2017-07-13T14:53:47.517

Does any truthy/falsy value count or do we need two distinct values? – Erik the Outgolfer – 2017-07-13T15:22:49.817

@EriktheOutgolfer any value – Skidsdev – 2017-07-13T15:35:22.007

6

Aka A072600, if this helps anybody.

– dcsohl – 2017-07-13T17:59:32.490

What about 0? Is it an allowed input, and if so, is it considered non-heavy? It's kind of a degenerate case. Oh nvm, you said positive, which rules out 0. – Peter Cordes – 2017-07-14T16:40:52.810

I will call such numbers "flaggy". – IllidanS4 wants Monica back – 2017-07-16T13:17:35.887

@IllidanS4 just make sure you don't miss out the l – Skidsdev – 2017-07-16T17:24:19.217

Answers

28

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.

ZH Liu

Posted 2017-07-13T14:26:46.563

Reputation: 401

Nice. I'd got as far as the obvious popcnt before scrolling down to look at answers, but hadn't thought of lzcnt for dealing with only the significant digits as required by the question. – Peter Cordes – 2017-07-14T16:42:55.670

Is there any way to get a net savings from using bsr instead of lzcnt (aka rep bsr)? You'd have to use sub instead of lea since it gives you 32-lzcnt. (Or leaves the dst unmodified for src=0, on all existing Intel and AMD hardware. AMD even documents this behaviour, but Intel says undefined... Anyway, OP said positive, which rules out 0.) – Peter Cordes – 2017-07-14T16:44:01.473

1

I was definitely thinking along the same lines as @Peter, since the challenge does explicitly limit inputs to positive integers. In fact, I had a solution drafted using popcnt and bsr, but it was 17 bytes. I was thinking that was pretty good compared to the first asm answer I saw, but this clever lea trick beats the pants off of that. I also looked at comparing bsf and popcnt. But I'm not seeing any way this solution can be beat, even taking into account the 1 byte that you could save by dropping the rep prefix.

– Cody Gray – 2017-07-14T18:22:07.383

1salc isn't equivalent to setc al: the latter sets al to 1 if CF set, not to 255. – Ruslan – 2017-07-15T08:06:39.920

@Ruslan: Indeed, my mistake. Fixed now. – ZH Liu – 2017-07-15T13:02:02.310

1The actual equivalent of salc is sbb al, al, but you get a savings of 1 byte to encode it. By the way, it is documented by AMD, and it's widely supported by Intel, with the mnemonic even coming from Intel's P6 opcode map. So this one is actually pretty safe to use. Also, nice improvement here to think to use that instruction! This is basically what my original draft did, except (1) I'd used x86-64 code, so inc was twice as long to encode, and (2) I hadn't thought of salc, so I was doing the same work in a longer way. Too bad I can only upvote once. – Cody Gray – 2017-07-17T04:57:42.043

For the record, bsr = 31 - lzcnt, not 32 - lzcnt. (I think you got the code right, I'm just correcting my earlier comment.) – Peter Cordes – 2017-09-20T08:16:38.653

17

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.

Dennis

Posted 2017-07-13T14:26:46.563

Reputation: 196 637

Nice. I had Bo-S, but I couldn't find a 1-byte atom that would convert positive/non-positive into truthy/falsy... – ETHproductions – 2017-07-13T15:17:40.953

Logical or with −1, right? – Lynn – 2017-07-15T09:12:27.403

@Lynn Yes, indeed. Thanks. – Dennis – 2017-07-15T15:06:32.150

14 bytes – caird coinheringaahing – 2017-12-12T16:28:08.913

@cairdcoinheringaahing Thanks, but Æṃ didn't exist back then. – Dennis – 2017-12-12T18:01:11.083

Dennis is laying down the law :P – Christopher – 2017-12-12T21:29:22.280

14

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!

Rod

Posted 2017-07-13T14:26:46.563

Reputation: 17 588

2Does the leading 0 in the return of bin cause this solution problems? – Shadow – 2017-07-14T03:29:15.243

3@shadow There is no problem, because of the way max works. In the event of a tie, max will return the first value in the iterable that has the maximal value. This code uses that fact to make sure that 1 is returned in the event of a tie, which actually means there are more ones than zeros, since an extra zero was added by bin. It would actually be incorrect when written this way if not for the extra zero. – FryAmTheEggman – 2017-07-14T12:47:03.300

@FryAmTheEggman this is also true on the old answer, where the cmp returns 0 when they are both equals – Rod – 2017-07-14T13:54:19.293

11

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

Stewie Griffin

Posted 2017-07-13T14:26:46.563

Reputation: 43 471

Is the communications toolbox a standard part of Octave, or is it more akin to a library in other languages? – dcsohl – 2017-07-13T18:28:13.170

It's a package that comes with the installation. You have to specifically load it in some installations, and it's automatically loaded as standard in others. It's part of the standard on Octave-Online.net, so I'm using that as a reference. (The code must work in at least one interpreter that existed prior to the challenge). – Stewie Griffin – 2017-07-13T18:44:20.077

9

JavaScript (ES6), 36 34 bytes

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

ETHproductions

Posted 2017-07-13T14:26:46.563

Reputation: 47 880

f=(n,x=0)=>n?f(n>>>1,x+=n%2-.5):x>0 for 35 bytes. – ovs – 2017-07-13T16:27:28.520

Use n>>1 instead of n>>>1 to save a byte since input is never negative. – kamoroso94 – 2017-07-13T23:00:48.797

@kamoroso94 Thanks, but then it would fail on 2147483648. – ETHproductions – 2017-07-13T23:03:53.800

@ETHproductions Darn, and n/2|0 is no better :/ – kamoroso94 – 2017-07-13T23:09:46.570

9

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

nmjcman101

Posted 2017-07-13T14:26:46.563

Reputation: 3 274

8

Mathematica, 22 bytes

Saved one byte thanks to @MartinEnder and @JungHwanMin.

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

alephalpha

Posted 2017-07-13T14:26:46.563

Reputation: 23 988

2I think infix notation has higher precedence than @@. – Martin Ender – 2017-07-13T20:23:21.503

1-1 byte (as @MartinEnder noted): #>#2&@@#~DigitCount~2& – JungHwan Min – 2017-07-14T05:05:37.873

7

Python 3,  44  (thanks @c-mcavoy) 40 bytes

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

Try it online!

wrymug

Posted 2017-07-13T14:26:46.563

Reputation: 772

5Crossed out 44 is still 44 – JungHwan Min – 2017-07-14T05:05:59.047

7

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 .

Fatalize

Posted 2017-07-13T14:26:46.563

Reputation: 32 976

6

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!

cleblanc

Posted 2017-07-13T14:26:46.563

Reputation: 3 360

Based on OP's clarification, you can remove unsigned – musicman523 – 2017-07-13T15:14:04.950

Since nnn is positive, you can change n>>=1 to n/=2. I also think you can use ~n instead of n^-1, which should also allow you to change && to & – musicman523 – 2017-07-13T15:22:16.247

Weird things happen when I edit comments - "nnn" means n, and never mind about changing && to &, I don't think that would work. But changing it to * seems to work – musicman523 – 2017-07-13T15:28:13.253

@musicman523 The && was only to handle the unsigned case but since I only need to handle positive integers I can remove it all together. Good pouint about /= being shorter that >>= though, Thanks ! – cleblanc – 2017-07-13T15:32:16.693

You can save one byte changing n&1?++i:--1 to i+=n%2*2-1. You might also be able to get rid of >0 by stating that you will output zero for heavy and nonzero for not heavy – musicman523 – 2017-07-13T15:35:04.820

@musicman523 That's a nice trick to save another byte. I think true and false are already well defined in C so I won't push that issue. – cleblanc – 2017-07-13T15:39:37.163

Ignore what I said before - since i could be negative, you do indeed need >0 – musicman523 – 2017-07-13T15:41:23.020

6

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!

ბიმო

Posted 2017-07-13T14:26:46.563

Reputation: 15 345

Is there any particular reason why you use 8d 1f instead of 89 fb? – Ruslan – 2017-07-13T17:30:49.013

Also, I think you can replace 75 04 ff c0 eb 02 ff c8 with 8d 44 58 ff. – Ruslan – 2017-07-13T17:39:47.743

Not a particular one, no. If I'd do that, the condition would be eax >= 0 or I'm gonna need to flip the ebx register in the loop. – ბიმო – 2017-07-13T19:27:24.673

2The real question is, is there any particular reason why you're using that abominable AT&T syntax?!? Also, the disassembly and your disassembly both agree that you have add eax, 2+dec eax, but your comments suggest that you want to increment ebx, not eax. – Cody Gray – 2017-07-14T04:23:34.463

It's what I learned, it's pretty much standard on my platform and in the end it doesn't matter - they're both only syntactic sugar. Fixed now - thanks for pointing out. – ბიმო – 2017-07-14T12:18:18.423

Using lea (%rdi), %ebx instead of mov %edi, %ebx is weird. Both are two bytes, but mov would be more idiomatic (and run faster, so using lea this way is a bad habit for non-code-golf purposes). – Peter Cordes – 2017-07-14T17:03:26.470

1

You can replace jnz Next/add/dec (7 bytes) with lea -1(%rax, %rbx, 2), %eax (4 bytes) to do eax += 2*ebx - 1 (like in the other x86 machine-code answer). Then outside the loop, neg %eax (2 bytes) before shifting the sign bit to the bottom. Net saving of 1 byte. Or test %eax,%eax / setge %al would also work, if your return value is a bool or int8_t.

– Peter Cordes – 2017-07-14T17:17:33.987

BTW, %ebx is call-preserved in the x86-64 System V ABI. I'm guessing you're aiming for that since you're taking your input in %edi. You might as well use %edx or %ecx as your scratch reg so this function actually follows the calling convention and can be called directly from C for testing. – Peter Cordes – 2017-07-14T17:21:10.647

shr puts the bit shifted out into CF. You could use sbb %edx, %edx (2 bytes) to turn that into 0/-1 for use with LEA. But then the loop structure has to change, because you need to process the last bit shifted out after %edi becomes zero. Also possible: do something like sbb $-1, %eax to add 1 or 0, or adc $0, %eax to add 0 or 1. But then the final condition would be different than you get from adding -1 or +1. – Peter Cordes – 2017-07-14T17:27:10.007

Most likely this is an artifact from a previous experiment, was left unchanged and I didn't change it because (for me) code golf isn't about saving a few clock cycles. That's basically the same thing @Ruslan suggested, I tried that and it resulted in the same/more byte count - I'll have a look again. Thanks for your tips! – ბიმო – 2017-07-14T17:33:13.757

1@PeterCordes I think I know what happened, but I'm not sure: I might have not tried lea -1(%rax,rbx,2) but only lea -1(%eax,%eax,2) and wasted bytes this way.. Anyway, you both were right, I can save a byte like this. Thanks a lot (in return I'll change that lea to a mov while I'm at it)! – ბიმო – 2017-07-14T18:01:37.187

isn't about saving a few clock cycles. In code-golf, it's still a human-readability issue (for the disassembly). No need to obfuscate for no benefit. I usually look at compiler-output asm while tuning real code, so lea (%rdi), %ebx just looks bad to my eye. Runs on fewer ports on most CPUs, and can't be handled in the rename stage with zero latency on IvyBridge+ and AMD Ryzen. Anyway, re: avoiding address-size prefixes, see also https://stackoverflow.com/questions/34377711/which-2s-complement-integer-operations-can-be-used-without-zeroing-high-bits-in. – Peter Cordes – 2017-07-14T19:36:22.953

Let us continue this discussion in chat.

– ბიმო – 2017-07-14T19:38:59.010

Any reason you're not using POPCNT? https://www.felixcloutier.com/x86/popcnt it's a 4 byte instruction. We /are/ talking x86-64, and any new CPU supports it.

– moonheart08 – 2019-02-05T15:52:39.757

1

@moonheart08: I didn't know about that back then, but someone posted an answer which saved 7 bytes.

– ბიმო – 2019-02-07T16:10:43.443

6

R, 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!

Giuseppe

Posted 2017-07-13T14:26:46.563

Reputation: 21 077

Only saw your answer after posting mine... Anyway, you can use log2(n) instead of log(n,2) to save 1 byte – Maxim Mikhaylov – 2017-07-13T20:14:03.760

@MaxLawnboy ah, of course. Thanks! – Giuseppe – 2017-07-13T20:38:58.237

Golfed off another 12 bytes: https://codegolf.stackexchange.com/a/132396/59530

– JAD – 2017-07-14T10:23:39.607

5

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)
}

Brad Gilbert b2gills

Posted 2017-07-13T14:26:46.563

Reputation: 12 713

5

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!

nimi

Posted 2017-07-13T14:26:46.563

Reputation: 34 639

mod n 2 can be just n, and it's a byte shorter without an accumulator. Try it online! – Ørjan Johansen – 2017-07-13T15:38:24.150

5

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

Post Rock Garf Hunter

Posted 2017-07-13T14:26:46.563

Reputation: 55 382

5

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.

Neil

Posted 2017-07-13T14:26:46.563

Reputation: 95 035

${1} can be $+. Or you could use ! instead of 0 and then shorten 01|10 to .\b.. – Martin Ender – 2017-07-13T20:25:18.977

@MartinEnder Huh, does $+ do the right thing when the pattern contains a |? I wonder whether I could have used that before... – Neil – 2017-07-13T20:42:05.170

2no, $+ is super stupid and simply uses the group with the biggest number, whether it was used or not. It's only useful for golfing when you've got more than nine groups or in a situation like the one here, and I don't know why I'd ever use it in a production regex. – Martin Ender – 2017-07-13T20:43:38.437

5

R, 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

MickyT

Posted 2017-07-13T14:26:46.563

Reputation: 11 735

+1 neat solution! I didn't even know about intToBits – Giuseppe – 2017-07-13T21:12:06.730

Golfed off another 4 bytes: https://codegolf.stackexchange.com/a/132396/59530

– JAD – 2017-07-14T10:23:46.190

5

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:

F. George

Posted 2017-07-13T14:26:46.563

Reputation: 317

4

Pyth, 9 7 bytes

ehc2S.B

Try it here.

-2 thanks to FryAmTheEggman.

Erik the Outgolfer

Posted 2017-07-13T14:26:46.563

Reputation: 38 134

Another 9 byte approach: >ysJjQ2lJ – KarlKastor – 2017-07-13T17:11:12.633

17 bytes but I feel like there should still be something shorter... – FryAmTheEggman – 2017-07-13T21:06:01.967

@FryAmTheEggman Hmm...that could only work as a full program. (I knew there was a way to use .B!) – Erik the Outgolfer – 2017-07-14T09:08:12.247

4

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.

JAD

Posted 2017-07-13T14:26:46.563

Reputation: 2 898

4

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 1s with no 0s. These operations are actually done in unary; it's only conceptually that they are being done in binary.
  3. Compare this "binary string of 1s" 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 1s" 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.
)

Deadcode

Posted 2017-07-13T14:26:46.563

Reputation: 3 022

1-98 bytes – Grimmy – 2019-02-06T16:18:42.367

4

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!

Destroigo

Posted 2017-07-13T14:26:46.563

Reputation: 401

4

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, 11011000 → 11010100 → 11010010 → 11010001), which has no effect on the number's binary-heaviness. Otherwise, the rightmost 01 is deleted (for example 10111001 → 101110, or 1100111 → 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.

Grimmy

Posted 2017-07-13T14:26:46.563

Reputation: 12 521

2

While this is inspired by Deadcode's answer, the algorithm is different enough that I felt it deserved a separate answer rather than a comment.

– Grimmy – 2019-02-06T16:17:10.793

2

This is phenomenal, and exactly what I wanted to see (somebody blowing my regex out of the water with a much more concise algorithm). But your comments really don't explain it at all, and the commented 73-byte version of the regex does not even work (the backrefs \5 onward are off by one). I have studied this and explained and commented it in my answer (because StackExchange doesn't allow multiline replies).

– Deadcode – 2019-02-07T03:31:55.170

3

Jelly, 6 bytes

Bµċ0<S

Try it online!

Erik the Outgolfer

Posted 2017-07-13T14:26:46.563

Reputation: 38 134

Bo-S can be used to calculate the binary "weight" of the input, unfortunately the shortest way to use that appears to be Bo-S>0... – ETHproductions – 2017-07-13T15:11:02.787

@ETHproductions Yep, there's no "is positive" atom yet. – Erik the Outgolfer – 2017-07-13T15:17:01.733

Well apparently works :P – ETHproductions – 2017-07-13T15:18:29.263

3

J, 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 (/)

Dan Bron

Posted 2017-07-13T14:26:46.563

Reputation: 421

1(#<2*+/)@#: should save 1 unless I’m missing something. – FrownyFrog – 2017-12-12T17:58:15.623

3

Julia, 22 bytes

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

Tanj

Posted 2017-07-13T14:26:46.563

Reputation: 199

2

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!

Jörg Hülsermann

Posted 2017-07-13T14:26:46.563

Reputation: 13 026

2

Octave, 26 bytes

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

Try it online!

alephalpha

Posted 2017-07-13T14:26:46.563

Reputation: 23 988

2

You can do something with mode(dec2bin(a)-48)

– nmjcman101 – 2017-07-13T17:15:08.150

2

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!

musicman523

Posted 2017-07-13T14:26:46.563

Reputation: 4 472

2

C#, 82 bytes

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

TheLethalCoder

Posted 2017-07-13T14:26:46.563

Reputation: 6 930

You can trim some more by treating the string as an IEnumerable<char>. n=>{var s=Convert.ToString(n,2);return s.Count(c=>c=='1')>s.Length/2;} – GalacticCowboy – 2017-07-13T19:43:18.630

@GalacticCowboy That adds 11 bytes because you have to fully qualify Convert and include using System.Linq; (written shorter as namespace System.Linq{}). Nice idea just doesn't shave off enough to warrant the saving in this case. – TheLethalCoder – 2017-07-14T07:52:21.183

2

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;

Oliver

Posted 2017-07-13T14:26:46.563

Reputation: 7 160

2

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.

Renzo

Posted 2017-07-13T14:26:46.563

Reputation: 2 260

2

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

Wernisch

Posted 2017-07-13T14:26:46.563

Reputation: 2 534

2

R, 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!

Maxim Mikhaylov

Posted 2017-07-13T14:26:46.563

Reputation: 571

1Let's see...you can use strtoi instead of as.logical and instead of length(n) you can use sum(n|T) and then obviously you want 2*sum(n)>length(n), aaand you can use x=scan() instead of a function definition (I did the same!); those are just handy R golfing tips :) – Giuseppe – 2017-07-13T20:45:03.690

@Giuseppe Very neat shortcut with sum(n|T). Thanks! – Maxim Mikhaylov – 2017-07-13T21:51:47.570

2

Ruby, 39 bytes

->n{b=n.to_s 2;b.count(?1)>b.count(?0)}

Try it online!

Value Ink

Posted 2017-07-13T14:26:46.563

Reputation: 10 608

You only need check that the 1-count is more than half, so ->n{b=n.to_s 2;b.count(?1)>b.size/2} is 3 bytes shorter. – Chowlett – 2017-07-17T12:36:04.307

2

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

junkmail

Posted 2017-07-13T14:26:46.563

Reputation: 131

You can now try it online! (Though, it seems this solution gets stuck when 1 is given as input.)

– Phlarx – 2018-05-02T20:38:46.820

2

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!

JollyJoker

Posted 2017-07-13T14:26:46.563

Reputation: 381

Didn't even knew about bitCount. Nice answer! I had something like this in my mind: n->{String s=n.toString(n,2);return s.replace("0","").length()>s.length()/2;} – Kevin Cruijssen – 2017-07-14T07:57:47.793

@KevinCruijssen If you want to try another Java solution, I'd suggest a loop with n/=2 and n%2>0?i++:i--. Might be shorter; at least close. – JollyJoker – 2017-07-14T08:26:31.970

It would be simple to use numberOfLeadingZeros to get the length, but the method name is 20 letters long :(

– JollyJoker – 2017-07-14T13:29:36.660

If you use Java 9's JShell you don't need the import since java.math.* is imported implicitly. – David Conrad – 2017-08-03T15:13:54.257

@DavidConrad Thanks, it seems to have a usefult list of default imports for golfing

– JollyJoker – 2017-08-04T07:28:16.030

2

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

streetster

Posted 2017-07-13T14:26:46.563

Reputation: 3 635

2

k, 22 bytes

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

q translation:

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

Interpreter available here

skeevey

Posted 2017-07-13T14:26:46.563

Reputation: 4 139

2

Python, 33 bytes

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

Try it online!

Anders Kaseorg

Posted 2017-07-13T14:26:46.563

Reputation: 29 242

2

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

scottinet

Posted 2017-07-13T14:26:46.563

Reputation: 981

2

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.

DLosc

Posted 2017-07-13T14:26:46.563

Reputation: 21 213

1

05AB1E, 8 6 bytes

-2 bytes thanks to Erik the Outgolfer

b1Ý¢`‹

Try it online! or Try all tests

Riley

Posted 2017-07-13T14:26:46.563

Reputation: 11 345

b{γ€g¥ is what I've tied you with ;). – Magic Octopus Urn – 2017-07-17T22:41:00.407

1

Pari/GP, 27 bytes

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

Try it online!

alephalpha

Posted 2017-07-13T14:26:46.563

Reputation: 23 988

1

GolfScript, 15 bytes

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

Try it online!

Erik the Outgolfer

Posted 2017-07-13T14:26:46.563

Reputation: 38 134

1

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.

TessellatingHeckler

Posted 2017-07-13T14:26:46.563

Reputation: 2 412

1

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.

Conor O'Brien

Posted 2017-07-13T14:26:46.563

Reputation: 36 228

1

TI-Basic, 29 bytes

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

Oki

Posted 2017-07-13T14:26:46.563

Reputation: 311

1

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

geokavel

Posted 2017-07-13T14:26:46.563

Reputation: 6 352

1

Rust, 30 bytes

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

Try it online!

Anders Kaseorg

Posted 2017-07-13T14:26:46.563

Reputation: 29 242

1

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.

Oyarsa

Posted 2017-07-13T14:26:46.563

Reputation: 136

You can use the -r flag in GNU sed to avoid escaping parentheses. Also you can use unnamed labels (empty label) instead of the u label to save two further bytes. Also, s/10//;s/01// can become s/10|01//. – user41805 – 2017-07-15T08:47:01.997

1

05AB1E, 6 bytes

b{γ€g¥

Try it online!

Results:

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

Magic Octopus Urn

Posted 2017-07-13T14:26:46.563

Reputation: 19 422

1

Ruby, 30 27 bytes

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

Try it online!

G B

Posted 2017-07-13T14:26:46.563

Reputation: 11 099

1

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

Conor O'Brien

Posted 2017-07-13T14:26:46.563

Reputation: 36 228

1

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  

reffu

Posted 2017-07-13T14:26:46.563

Reputation: 1 361

1

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.

Jo King

Posted 2017-07-13T14:26:46.563

Reputation: 38 234

0

CJam, 11 bytes

2,ri2bfe=:<

Try it online!

Erik the Outgolfer

Posted 2017-07-13T14:26:46.563

Reputation: 38 134

@MartinEnder How does :< work in your example? If it's a quick fold or quick map, I don't really get it. – geokavel – 2017-07-14T02:46:39.900

@geokavel I just noticed it doesn't work when the input contains only 0-bits or only 1-bits so nevermind. – Martin Ender – 2017-07-14T04:59:03.937

@EriktheOutgolfer I suggested sorting, RLE, comparison, but that assumes that both zero and one are present in the number. – Martin Ender – 2017-07-14T09:12:11.230

@MartinEnder Oh yeah RLE is a big no here. I think you suggested ri2b$e\0f=:<` which is longer anyways. – Erik the Outgolfer – 2017-07-14T09:13:47.070

0

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)

Jim

Posted 2017-07-13T14:26:46.563

Reputation: 1 442

Probably? – Erik the Outgolfer – 2017-07-13T15:25:19.690

3@EriktheOutgolfer At least mine has an explanation. – Jim – 2017-07-13T15:32:53.227

0

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.

Esolanging Fruit

Posted 2017-07-13T14:26:46.563

Reputation: 13 542

0

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

Roman Gräf

Posted 2017-07-13T14:26:46.563

Reputation: 2 915

0

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

Daniel

Posted 2017-07-13T14:26:46.563

Reputation: 101

-11 bytes: func h(b:Int){let a=String(b,radix:2).characters;print(a.filter{$1=="1"}.count>a.count/2)} – Herman L – 2017-12-12T16:53:51.473

-22 bytes with Swift 4 func h(b:Int){let a=String(b,radix:2);print(a.filter{$1=="1"}.count>a.count/2)} – Herman L – 2017-12-12T16:58:02.923

0

Perl 5, 33 bytes

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

Try it online!

Xcali

Posted 2017-07-13T14:26:46.563

Reputation: 7 671

0

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

Shaggy

Posted 2017-07-13T14:26:46.563

Reputation: 24 623

0

Add++, 12 bytes

L,BBEDdb!Es<

Try it online!

caird coinheringaahing

Posted 2017-07-13T14:26:46.563

Reputation: 13 702

0

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!

RiaD

Posted 2017-07-13T14:26:46.563

Reputation: 101

0

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!

Giuseppe

Posted 2017-07-13T14:26:46.563

Reputation: 21 077

0

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.

ბიმო

Posted 2017-07-13T14:26:46.563

Reputation: 15 345

0

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)

mudkip201

Posted 2017-07-13T14:26:46.563

Reputation: 833

0

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

Stephen

Posted 2017-07-13T14:26:46.563

Reputation: 12 293

0

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

RosLuP

Posted 2017-07-13T14:26:46.563

Reputation: 3 036

0

Red, 74 bytes

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

Try it online!

Galen Ivanov

Posted 2017-07-13T14:26:46.563

Reputation: 13 815

0

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

F. Hauri

Posted 2017-07-13T14:26:46.563

Reputation: 2 654

0

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.

dana

Posted 2017-07-13T14:26:46.563

Reputation: 2 541

0

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

wooshinyobject

Posted 2017-07-13T14:26:46.563

Reputation: 171

0

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

RosLuP

Posted 2017-07-13T14:26:46.563

Reputation: 3 036

Could you specify the compiler you used? – Jonathan Frech – 2019-02-06T10:23:28.190

Possibly f(n,a){for(a=0;n;n/=2)a+=n%2*2-1;a=a>0;}? – Jonathan Frech – 2019-02-06T10:25:29.187

@JonathanFrech each C compiler – RosLuP – 2019-02-06T12:24:57.343

I would think there are a lot of C compilers out there. Do you mean C89 compliant or something along those lines? – Jonathan Frech – 2019-02-06T19:39:49.513

Yes C89 standard (I hope at last)... It would be good for me to know some C compiler not compile above code – RosLuP – 2019-02-07T10:10:00.203

Would it not be C89 compliant if one threw an error upon encountering a declaration-less variable declaration, e.g. f(n)? – Jonathan Frech – 2019-02-07T12:56:01.657

For me show some warning but compile – RosLuP – 2019-02-07T13:26:58.987

0

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!

Hille

Posted 2017-07-13T14:26:46.563

Reputation: 349

0

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

recursive

Posted 2017-07-13T14:26:46.563

Reputation: 8 616