[Question]
  [
Given an integer `n > 0`, output the length of the longest contiguous sequence of `0` or `1` in its binary representation.
**Examples**
* `6` is written `110` in binary; the longest sequence is `11`, so we
should return `2`
* `16` → `10000` → `4`
* `893` → `1101111101` → `5`
* `1337371` → `101000110100000011011` → `6`
* `1` → `1` → `1`
* `9965546` → `100110000000111111101010` → `7`
  
[Answer]
# [Python 2](https://docs.python.org/2/), ~~46~~ 45 bytes
```
f=lambda n,k=1:`k`in bin(n^n/2)and-~f(n,k*10)
```
[Try it online!](https://tio.run/nexus/python2#DYxBCoMwFAXX7SneJmgk0qbRpBHsUYqREAjqV8R1r57@xYOBN0xJ4xq2OQaQWkY9TMuUCXOmmr70eMlAsf2lms9GP2VJ@wkCG1ZB897eMBjjjNMMCt7bvu/scL8dZ6YLlXAR7QciVhDgDjgmZfkD "Python 2 – TIO Nexus")
### How it works
By XORing **n** and **n/2** (dividing by **2** essentially chops off the last bit), we get a new integer **m** whose unset bits indicate matching adjacent bits in **n**.
For example, if **n = 1337371**, we have the following.
```
n    = 1337371 = 101000110100000011011₂
n/2  =  668685 =  10100011010000001101₂
m    = 1989654 = 111100101110000010110₂
```
This reduces the task to find the longest run of zeroes. Since the binary representation of a positive integer always begins with a **1**, we'll try to find the longest **10\*** string of digits that appears in the binary representation of **m**. This can be done recursively.
Initialize **k** as **1**. Every time **f** is executed, we first test if the decimal representation of **k** appears in the binary representation of **m**. If it does, we multiply **k** by **10** and call **f** again. If it doesn't, the code to the right of `and` isn't executed and we return *False*.
To do this, we first compute `bin(k)[3:]`. In our example, `bin(k)` returns `'0b111100101110000010110'`, and the `0b1` at the beginning is removed with `[3:]`.
Now, the `-~` before the recursive call increments *False*/**0** once for every time **f** is called recursively. Once **10{j}** (**1** followed by **j** repetitions of **0**) does not appear in the binary representation of **k**, the longest run of zeroes in **k** has length **j - 1**. Since **j - 1** consecutive zeroes in **k** indicate **j** matching adjacent bits in **n**, the desired result is **j**, which is what we obtain by incrementing *False*/**0** a total of **j** times.
[Answer]
## Python 2, 46 bytes
```
f=lambda n,r=1:max(r,n and f(n/2,1+~-n/2%2*r))
```
[Try it online](https://tio.run/nexus/python2#FYzBCsIwEAXP@hXvEprqFtmsGC3Uf4mEQMFuZfHgyV@v62GYOc3WpmdZHrVAySYel/KJRoqiFS3qKREfv4M7pIP1/dZWg2JWMOFCYEc8OZ0J15t4iWTJPO53L5v1jS7kiuGOUDsERKX/1kc/)
Extracts binary digits from `n` in reverse by repeatedly taking `n/2` and `n%2`. Tracks the length of the current run `r` of equal digits by resetting it to 0 if the last two digits are unequal, then adding 1. 
The expression `~-n/2%2` is an indicator of whether the last two digits are equal, i.e. `n` is 0 or 3 modulo 4. Checking the last two digits together turned out shorten than remembering the previous digit.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
b.¡€gM
```
[Try it online!](https://tio.run/nexus/05ab1e#@5@kd2jho6Y16b7//xsaG5sbmxsCAA "05AB1E – TIO Nexus")
**Explanation**
```
b       # convert to binary
 .¡     # split at difference
   €g   # map length on each
     M  # take max
```
[Answer]
## Mathematica, 38 bytes
```
Max[Length/@Split[#~IntegerDigits~2]]&
```
or
```
Max[Tr/@(1^Split[#~IntegerDigits~2])]&
```
[Answer]
# Python, 53 bytes
```
import re;lambda g:max(map(len,re.findall('1+|0+',bin(g))))
```
Anonymous lambda function.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
BŒgL€Ṁ
```
[Try it online!](https://tio.run/nexus/jelly#@@90dFK6z6OmNQ93Nvw/3A5k/P8fbaajYAjEFpbGQIaxsbmxuWEsAA "Jelly – TIO Nexus")
### How it works
```
BŒgL€Ṁ  Main link. Argument: n
B       Binary; convert n to base 2.
 Œg     Group adjacent, identical elements.
   L€   Map length over the groups.
     Ṁ  Take the maximum.
```
[Answer]
## Ruby, ~~41~~ 40 bytes
```
->b{("%b%b"%[b,~b]).scan(/1+/).max.size}
```
Find longest sequence of '1' in b or its inverse.
Thanks to manatwork for saving 1 byte.
[Answer]
# JavaScript (ES6), 54 bytes
```
f=(n,r=0,l=1,d=2)=>n?f(n>>1,d^n&1?1:++r,r>l?r:l,n&1):l
```
A recursive solution with a lot of bit manipulation. `n` stores the input, `r` stores the length of the current run, `l` stores the length of the longest run, and `d` stores the previous digit.
### Test snippet
```
f=(n,r=0,l=1,d=2)=>n?f(n>>1,d^n&1?1:++r,r>l?r:l,n&1):l
for(var i of [0,1,2,3,4,5,6,7,8,9,16,893,1337371]) console.log(`f(${i}): ${f(i)}`)
```
[Answer]
# Perl, 43 bytes
```
#!perl -p
\@a[$a+=$_-1+($_>>=1)&1||-$a]while$_;$_=@a
```
Counting the shebang as one, input is taken from stdin.
[Try it online!](https://tio.run/nexus/perl#@x/jkBitkqhtqxKva6itoRJvZ2drqKlmWFOjq5IYW56RmZOqEm@tEm/rkPj/v4Wl8X/dAgA "Perl – TIO Nexus")
[Answer]
# Ruby, ~~51~~ ~~44~~ 43 bytes
Function solution.
@manatwork is made of magic
```
->s{('%b'%s).scan(/0+|1+/).map(&:size).max}
```
[Answer]
# Python 2, 57 bytes
```
a=lambda n:n and max((n&-n|~n&-~n).bit_length()-1,a(n/2))
```
A recursive solution. There might be a shorter form for the bit magic.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 16 bytes
Seems like there's gotta be a shorter way to get the runs of same digit...
```
MX#*(TBa`1+|0+`)
```
Takes input as command-line argument. [Try it online!](https://tio.run/nexus/pip#@@8boaylEeKUmGCoXWOgnaD5//9/QzMA "Pip – TIO Nexus")
### Explanation
```
     TBa          1st cmdline arg, To Binary
    (   `1+|0+`)  Find all matches of this regex
  #*              Map length operator to that list
MX                Get the maximum and autoprint it
```
[Answer]
# [Perl 6](http://perl6.org/), 36 bytes
```
{(.base(2)~~m:g/1+|0+/)».chars.max}
```
Explanation:
```
{                                 }   # a lambda
  .base(2)                            # convert the argument to base 2
          ~~m:g/     /                # regex match, with global matching turned on
                1+|0+                 # match one or more 1, or one or more 0
 (                    )».chars        # replace each match by its length
                              .max    # take the maximum number
```
[Try it online](https://glot.io/snippets/em52gi3o7f).
[Answer]
## Haskell, 79 characters
```
maximum.map length.group.i
```
where
```
import Data.List
i 0=[]
i n=mod n 2:i(div n 2)
```
Or in ungolfed version:
```
import Data.List
pcg :: Int -> Int
pcg = maximum . map length . group . intToBin
intToBin :: Int -> [Int]
intToBin 0 = []
intToBin n = n `mod` 2 : intToBin (n `div` 2)
```
## Explanation:
`intToBin` converts an int to a list of binary digits (lsb first). `group` groups contiguous sequences, such that `[1, 1, 0, 0, 0, 1]` becomes `[[1, 1],[0, 0, 0],[1]]`. `maximum . map length` calculates for each inner list its length and returns the length of the longest.
Edit: Thanks to @xnor and @Laikoni for saving bytes
[Answer]
# Pyth, 7 bytes
```
heSr8.B
```
Do run length encode on the binary string, then sort it so that the longest runs come last, then take the first element (the length) of the last element (the longest run) of the list.
In pseudocode:
```
'  S     ' sorted(
'   r8   '   run_length_encode(
'     .BQ'     bin(input()) ))  \
'he      '   [-1][0]
```
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
[:>./#:#;.1~1,2~:/\#:
```
[Try it online!](https://tio.run/nexus/j#@5@mYGulEG1lp6evbKVsrWdYZ6hjVGelH6NsxZWanJGvoKGjl6ZkoKlgpmBopmBhaaxgaGxsbmxu@P8/AA "J – TIO Nexus")
## Explanation
```
[:>./#:#;.1~1,2~:/\#:  Input: integer n
                   #:  Binary digits of n
              2   \    For each continuous subarray of 2 digits
               ~:/       Reduce it using not-equals
            1,         Prepend a 1 to those results
     #:                Binary digits of n
        ;.1~           Cut the binary digits at each location with a 1
       #                 Get the length of each cut
[:>./                  Reduce those lengths using maximum and return
```
[Answer]
**MATLAB** 71 bytes
```
m=1;a=diff(int8(dec2bin(a)));while(any(a==0)),m=m+1;a=diff(a);end;m
```
This converts integer variable 'a' to a binary int8 array then counts the number of times the result has to be differentiated until there is no zero in the result.
I am new here. Is this sort of input and one-liner allowed by the PCG rules?
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 31 bytes
```
@(n)max(runlength(+dec2bin(n)))
```
[Try it online!](https://tio.run/nexus/octave#@@@gkaeZm1ihUVSal5Oal16SoaGdkppslJSZB5TQ1PyfpmCrkJhXbM2VpmGmqaOQpmEIoSwsjSFcY2NzY3NDCFvzPwA "Octave – TIO Nexus")
### Explanation
This is a translation of my MATL answer. My initial plan was a different approach, namely `@(n)max(diff(find(diff([0 +dec2bin(n) 0]))))`. But it turns out that Octave has a [`runlength`](https://octave.sourceforge.io/octave/function/runlength.html) function (which I just found out about). By default it outputs only the array of run-lengths, so the desired result is the `max` of that array. The output of `dec2bin`, which is a char array (string) containing `'0'` and `'1'`, needs to be converted to a numeric array using `+`, because `runlength` expects numeric input.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) / Unix utilities, ~~66~~ ~~65~~ 42 bytes
Thanks to @DigitalTrauma for significant improvements (23 bytes!).
```
dc<<<`dc -e2o?p|fold -1|uniq -c|sort -n`rp
```
[Try it online!](https://tio.run/nexus/bash#@5@SbGNjk5CSrKCbapRvX1CTlp@ToqBrWFOal1mooJtcU5xfVKKgm5dQVPD/v6WlmampiRkA "Bash – TIO Nexus")
[Answer]
# Bash (+coreutils, +GNU grep), ~~33~~, 32 bytes
EDITS:
* Minus 1 byte (removed quotes around *grep* expression)
**Golfed**
```
dc -e2o$1p|grep -Po 1+\|0+|wc -L
```
**Explained**
```
 #Convert to binary
 >dc -e2o893p
 1101111101
 #Place each continuous run of 1es or 0es on its own line
 >dc -e2o893p|grep -Po '1+|0+'
 11
 0
 11111
 0
 1
 #Output the length of the longest line
 >dc -e2o893p|grep -Po '1+|0+'|wc -L
 5
```
[Try It Online!](https://tio.run/nexus/bash#@5@SrKCbapRvX1CTXpRaoKAbkK9gqB1TY6BdUw6U8fn/39LSzNTUxAwA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 4 bytes
```
bøef
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQRyIsIiIsImLDuGVmIiwiIiwiODkzIl0=)
Abuses the `G` flag which returns the maximum value of the item on top of the stack.
```
b      # convert input to binary
  øef  # run_length_encoding and flatten 2D -> 1D
       # Implicitly take the largest value in the flattened array
```
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), ~~41~~ 38 bytes
```
~:digits&2|:slice_when+:!=|:*&:+@|:max
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN9XqrFIy0zNLitWMaqyKczKTU-PLM1LztK0UbWustNSstB1qrHITK6CqLQoU3KLNYrlAlCGUtrA0hgoYG5sbmxtCORDK0tLM1NTELBaif8ECCA0A)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
$b@b:lotl
```
[Try it online!](https://tio.run/nexus/brachylog#@6@S5JBklZNfkvP/v6GxsbmxueH/KAA "Brachylog – TIO Nexus")
### Explanation
```
$b          List of binary digits of the input
  @b        Runs of consecutive identical digits in that list
    :lo     Order those runs by length
       tl   Output is the length of the last one
```
[Answer]
## C#, 106 bytes
```
n=>{int l=1,o=0,p=0;foreach(var c in System.Convert.ToString(n,2)){o=c!=p?1:o+1;l=o>l?o:l;p=c;}return l;};
```
Formatted version:
```
System.Func<int, int> f = n =>
{
    int l = 1, o = 0, p = 0;
    foreach (var c in System.Convert.ToString(n, 2))
    {
        o = c != p ? 1 : o + 1;
        l = o > l ? o : l;
        p = c;
    }
    return l;
};
```
And an alternative approach accessing the string by index at 118 bytes, with whitespace removed:
```
System.Func<int, int> f2 = n =>
{
    var s = System.Convert.ToString(n, 2);
    int l = 1, c = 1, i = 0;
    for (; i < s.Length - 1; )
    {
        c = s[i] == s[++i] ? c + 1 : 1;
        l = l < c ? c : l;
    }
    return l;
};
```
[Answer]
# Javascript, 66 Bytes
```
x=>Math.max(...x.toString(2).split(/(0+|1+)/g).map(y=>y.leng‌​th))
```
Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for the code.
### Explanation
```
x.toString(2)
```
Convert number to binary string.
```
split(/(0+|1+)/g)
```
Split every different character (0 or 1) (this regex captures empty spaces but they can be ignored)
```
map(y=>y.length)
```
For each element of the array get its length and put it in the returned array.
```
...
```
Convert array to list of arguments ([1,2,3] -> 1,2,3)
```
Math.max()
```
Get the largest number out of the arguments.
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 27 bytes
```
max.map#len.mstr`0+|1+`g.bn
```
Usage:
```
(max.map#len.mstr`0+|1+`g.bn)123
```
Converts to binary, matches each sequence of 0's and 1's, gets the length of each match, and gets the maximum.
[Answer]
## Batch, 102 bytes
```
@set/a"n=%1/2,d=%1%%2,r=1+(%3+0)*!(0%2^d),l=%4-(%4-r>>5)
@if not %n%==0 %0 %n% %d% %r% %l%
@echo %l%
```
Port of @edc65's answer. `%2`..`%4` will be empty on the first call, so I have to write the expressions in such a way that they will still work. The most general case is `%3` which I had to write as `(%3+0)`. `%2` is easier, as it can only be `0` or `1`, which are the same in octal, so `0%2` works here. `%4` turned out to be even easier, as I only need to subtract from it. `(%4-r>>5)` is used to compare `l` with `r` as Batch's `set/a` doesn't have a comparison operator.
[Answer]
# [Dyalog APL](http://dyalog.com/download-zone.htm), 22 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Anonymous function train
```
⌈/∘(≢¨⊢⊂⍨1,2≠/⊢)2⊥⍣¯1⊢
```
`⌈/∘(`... The maximum of the results of the following anonymous function-train...
 `≢¨`  the tally of each
 `⊢⊂⍨` partition of the argument, where the partitioning is determined by the ones in
 `1,` one prepended to
 `2≠/` the pairwise unequal of
 `⊢` the argument
`)` applied to
`2⊥⍣¯1` from-base-2 applied negative one times (i.e. to-base-2, once) to
`⊢` the argument
[TryAPL online!](http://tryapl.org/?a=f%u2190%u2308/%u2218%28%u2262%A8%u22A2%u2282%u23681%2C2%u2260/%u22A2%292%u22A5%u2363%AF1%u22A2%20%u22C4%20f%A8%206%2016%20893%201337371%201%209965546&run)
[Answer]
# Japt, 15 bytes
```
2o!q¢ c ml n gJ
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=Mm8hcaIgYyBtbCBuIGdK&input=ODkz) or [Verify all test cases at once](http://ethproductions.github.io/japt/?v=1.4.3&code=Tm1VezJvIXGiIGMgbWwgbiBnSn0gcVI=&input=MQo2CjE2Cjg5MwoxMzM3MzcxCjk5NjU1NDY=).
### How it works
```
                 // Implicit: U = input integer, J = -1
2o               // Create the range [0...2), or [0,1].
  ! ¢            // Map each item Z in this range to U.s(2)
   q             //                                        .q(Z).
                 // This returns the runs of 1's and 0's in the binary
                 // representation of U, respectively.
      c          // Flatten into a single list.
        ml       // Map each item Z to Z.length.
           n gJ  // Sort the result and grab the item at index -1, or the last item.
                 // This returns the largest element in the list.
                 // Implicit: output result of last expression
```
[Answer]
## R, 45 34 bytes
```
max(rle(miscFuncs::bin(scan()))$l)
```
Fixed a silly misunderstanding thanks to @rturnbull and @plannapus.
]