[Question]
  [
# BCD difference
Given an integer n, convert it to BCD ([binary-coded decimal](https://en.wikipedia.org/wiki/Binary-coded_decimal#Basics)) by replacing each decimal digit with its 4-digit binary representation
```
 234 -> 0 0 1 0 0 0 1 1 0 1 0 0
```
Then rotate the list of binary digits in order to find the largest and smallest numbers, representable by this list without other rearrangements.
```
max: 1 1 0 1 0 0 0 0 1 0 0 0  (the entire list rotated left 6 times)
min: 0 0 0 0 1 0 0 0 1 1 0 1 (the entire list rotated right 2 times)
```
Convert these numbers back to decimal, treating the list of bits as regular binary and subtract the smallest from the largest:
```
1 1 0 1 0 0 0 0 1 0 0 0 -> 3336
0 0 0 0 1 0 0 0 1 1 0 1 -> 141
3336 - 141 -> 3195
```
The output is the difference of the largest and smallest numbers found.
Test cases:
```
234 -> 3195
1234 -> 52155
12 -> 135
975831 -> 14996295
4390742 -> 235954919
9752348061 -> 1002931578825
```
  
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~89~~ 88 bytes
*Thanks to Jenny\_mathy for saving 1 byte.*
```
i=IntegerDigits;Max@#-Min@#&[#~FromDigits~2&/@NestList[RotateRight,Join@@i[i@#,2,4],#]]&
```
[Try it online!](https://tio.run/##JcqxCsIwEIDhVwkEgkKkUFyKCCcUwWJFuoYMh4T0hiSQ3FCXvHosOP3D9wfk1QVk@mB7Z4osOhCHRtdHZOddHskTl8uMG8jTTBGkMrLecwp/qb3q4OUKP6mwWRIju4X8ynpK@w1kCKTu9dlqaa1qR1HFLWf87h2G9gM "Wolfram Language (Mathematica) – Try It Online")
This is terribly inefficient, because it generates **n** rotations of the BCD of **n**, which is way more than we need. We can make this is a bit more efficient by saving the result of the `Join@@` in `k` and replacing the `#` at the end with `Length@k`. That lets us generate a scatterplot quite easily:
[![enter image description here](https://i.stack.imgur.com/ejAnA.png)](https://i.stack.imgur.com/ejAnA.png)
I'm really intrigued by the contrast of local structure and overall chaos.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
Dd4d2FṙJ$ḄṢIS
```
[Try it online!](https://tio.run/##y0rNyan8/98lxSTFyO3hzpleKg93tDzcucgz@P/RPYfbHzWtcf//38jYREfBEErqKFiam1oYG@oomBhbGpibQASAkhYGZoYA "Jelly – Try It Online")
### How it works
```
Dd4d2FṙJ$ḄṢIS  Main link. Argument: n
D              Decimal; convert n to base 10 (digit array).
 d4            Divmod 4; map each digit d to [d/4, d%4].
   d2          Divmod 2; map each [d/4, d%4] to [[d/8, d/4%2], [d%4/2, d%2]].
     F         Flatten the resulting 3D binary array.
      ṙJ$      Take all possible rotations.
         Ḅ     Convert each rotation from binary to integer.
          Ṣ    Sort the resulting integer array.
           I   Take the forward differences.
            S  Take the sum.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~115~~ 108 bytes
*thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) for -7 bytes*
```
k=''.join(f'{int(i):04b}'for i in input())
v=[int(k[i:]+k[:i],2)for i in range(len(k))]
print(max(v)-min(v))
```
[Try it online!](https://tio.run/##PY3LCoMwFET3@Qpxk3v7Qk3qC/yS4MLa2KapiYgVS@m3p7GFwjAwzGFmeE5Xa5hr7VlWYRg6XVF6uFlloKMvZSZQWEb89KadHQMVKOM1PCZAJHMlVkALVdZbLUpV7xL8Y2NjLhLu0oBGrMkwrmzfLDDjvvfzM6Lzh0QusoX1fpOiSxgn8c9IkR1zFhPOiijj3@iLPErjDw "Python 3 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 153 bytes
```
$b=[char[]]-join([char[]]"$args"|%{[convert]::toString(+"$_",2).PadLeft(4,'0')})
($c=$b|%{$x,$y=$b;[convert]::ToInt64(-join($b=$y+$x),2)}|sort)[-1]-$c[0]
```
[Try it online!](https://tio.run/##TY3RCoIwGEbve4zxhxtqqJmV4QMEXQR1N0boWmrIFnOUkj77EiLo7vsuzjkP9RK6rUTTWAtFRnmVa8qYf1e1xL@HINdli4b5m3Iln0IblqZGnYyuZYldBBfkRWRxzK8HcTM49pzAISOZYeAZFBMGnQf9NHd//FntpUli/E1Nbehd6MgkGodWaUOoHzIfOA2YtXa7XkXLeBMk4Qc "PowerShell – Try It Online")
Stupid lengthy .NET calls to convert to/from binary really bloats the length here. ;-)
We take input as `$args`, wrap it in a string, then cast it as a `char`-array. We loop over each digit, `convert`ing the digit `toString` in base `2` (i.e., turning the digit into a binary number), then `.padLeft` to make it a four-digit binary number. That resulting array of strings is then `-join`ed into a single string and re-cast as a `char`-array before being saved into `$b`.
Next, we loop over `$b`, which just makes sure we loop enough times to account for every rotation. Each iteration, we peel off the first character into `$x` and the remaining characters into `$y` using multiple assignment. Then, we merge them back together into `$b=$y+$x` to move the first element to the end, i.e., effectively rotating the array by one. That's `-join`ed into a string, which is used as the input to the `convert` call to turn the string from binary base `2` into an `Int64`. We then `sort` all of those resultant numbers and store them into `$c`. Finally, we take the biggest `[-1]` and subtract the smallest `[0]`. That's left on the pipeline and output is implicit.
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), 15 bytes
```
€b4Ü. 0\;Jγó↕]a
```
[Try it online!](https://tio.run/##y8/INfr//1HTmiSTw3P0FAxirL3ObT68@VHb1NjE//@NjE0A "Ohm v2 – Try It Online")
Explanation:
```
€b4Ü. 0\;Jγó↕]a  Main wire, arguments: a (integer)
€       ;        Map the following over each digit of a...
 b                 Convert to binary
  4Ü               Right-justify w/ spaces to length 4
    . 0\           Replace all spaces with zeroes
         J       Join together binary digits
          γó     Get all possible rotations and convert back to decimal
            ↕    Find the minimum *and* maximum rotation
             ]a  Flatten onto stack and get the absolute difference
```
[Answer]
## JavaScript (ES6), ~~118~~ ~~100~~ 99 bytes
```
f=
n=>(g=m=>Math[m](...[...s=(`0x1`+n-0).toString(2)].map(_=>`0b${s=0+s.slice(2)+s[1]}`)))`max`-g`min`
```
```
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>
```
Edit: Saved 11 bytes thanks to @RickHitchcock. Saved 1 byte thanks to @ETHproductions. Explanation: The `0x1` prefix causes the input to get reparsed as a hexadecimal number, whose binary is the same as the BCD of the original number with a 1 prefix (I think this is golfier than any other way of padding to a multiple of 4 digits). Excluding the prefix, which is changed from 1 to 0, the resulting string is then rotated at each possible position and converted from binary back to decimal. Finally the maximum and minimum are subtracted.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~115~~ 113 bytes
* Saved some bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
* Saved two bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
```
b="".join(format(int(n),"04b")for n in`input()`)
b=[int(b[s:]+b[:s],2)for s in range(len(b))]
print max(b)-min(b)
```
[Try it online!](https://tio.run/##LY7BjoMgEIbvPgWZE2RtIyBVbNxLH8M1Vla6ZaNokKbdp3eh7WUy3@Sb@Wf589fZsm3QF2TscvOYVEPddWZaZue7DoO6mdEbuwLZu/7evaX9uozGY0C7TwTkuDhjPRoa2qbwZesa0qPT/uZsOOrx0GQtSU41AGwq1P3vbCy@zG7qPY6CJSlkuQISZijunN8xZ5KouomKataq/VBNtbYpe3pr8JDr7Y/Go7ZYEdImrz@m/hFwN5k43ULqUT/0N9yvZtToVEVAJ9gYz@P7nEqR0DcIRkWk2FMuElmIktMn5VIeWFBzLrMifxqMCylySWX0woUyO7zcLGOSU1GUJRP/ "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29 bytes
```
Ksm.[\04.Bsd`Q-eJSmi.<Kd2lKhJ
```
[Try it here!](https://pyth.herokuapp.com/?code=Ksm.%5B%5C04.Bsd%60Q-eJSmi.%3CKd2lKhJ&input=234&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0) or [Check out the test suite.](https://pyth.herokuapp.com/?code=Ksm.%5B%5C04.Bsd%60Q-eJSmi.%3CKd2lKhJ&input=234&test_suite=1&test_suite_input=234%0A1234%0A12%0A975831%0A4390742%0A9752348061&debug=0)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
§-▼▲mḋUMṙNṁȯtḋ+16d
```
[Try it online!](https://tio.run/##yygtzv6vcGhbrkawzqOmxv@Hlus@mrbn0bRNuQ93dIf6Ptw50@/hzsYT60uAXG1Ds5T///9HGxmb6BhCCB1Lc1MLY0MdE2NLA3MTMBcoYWFgZhgLAA "Husk – Try It Online")
There should be a shorter way to convert a digit into its 4-bit binary representation...
### Explanation
```
§-▼▲mḋUMṙNṁȯtḋ+16d
                 d    Get the list of digits of the input
          ṁȯ          For each digit...
              +16      add 16
             ḋ         convert to binary
            t          drop the first digit
       MṙN            Rotate the list by all possible (infinite) numbers
      U               Get all rotations before the first duplicated one
    mḋ                Convert each rotation from binary to int
§-▼▲                  Subtract the minimum from the maximum value
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 31 bytes
Full program body. Prompts for number from STDIN. Prints result to STDOUT.
```
(⌈/-⌊/)2⊥¨(⍳≢b)⌽¨⊂b←,⍉(4/2)⊤⍎¨⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQMCjtgmG5gqPeucqFBRl5pUoADnFmel5mWmZyYlAbkpmemZJsYJGVmlxiUIikFtckJNYqZBZXFyaqsn1qKM97b/Go54Ofd1HPV36mkaPupYeWqHxqHfzo85FSZqPevYeWvGoqykJaInOo95ODRN9I81HXUse9fYBxXvn/Qfq/68ABmlcRsYmXDC2ISoHzrQ0N7UwNoRzTYwtDcxNUKSBGi0MzAwB "APL (Dyalog Unicode) – Try It Online")
`⍞` prompt for line of text from STDIN
`⍎¨` execute (evaluate) each (character)
`(`…`)⊤` encode (anti-base) in the following number system:
 `4/2` four binary bits
`⍉` transpose
`,` ravel (flatten)
`b←` store in `b` (for *b*inary)
`⊂` enclose (so that we will use this entire list for each rotation)
`(`…`)⌽¨` rotate (left) by each of the following amounts:
`≢b` length of `b`
 `⍳` **i**ndices of that
`2⊥¨` decode each from base-2.
`(`…`)` apply the following tacit function to that
 `⌈/` the max(-reduction)
 `-` minus
 `⌊/` the min(-reduction)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~37~~ 34 bytes
```
{(⌈/-⌊/)2⊥¨(⍳⍵)∘.⌽⊂,↑(4⍴2)∘⊤¨⍎¨⍕⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqjUc9Hfq6j3q69DWNHnUtPbRC41Hv5ke9WzUfdczQe9Sz91FXk86jtokaJo96txiBBB91LTm04lFvH4iYClRYCzRI4dAKBSNjEwVDCKFgaW5qYWwIAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
DB0;$4¡€ṫ€-3FṙJ$ḄµṀ_Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8/9/FycBaxeTQwkdNax7uXA0kdY3dHu6c6aXycEfLoa0PdzbEP9zZ9P//fyNjEwA "Jelly – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~96~~ 91 bytes
```
->n{r=""
n.digits.map{|d|r="%04b"%d+r}
s=r.chars.map{(r=r[1..-1]+r[0]).to_i 2}
s.max-s.min}
```
[Try it online!](https://tio.run/##LY7LboMwEEX3/grLUaRWAcvPgBfOjyBUESCJF6VocKRUxt9OjdPNaO69Zx7wvP5uN7uVlymAJQRNdHB35xf63c1hHdZkHpm6kuNwgogWC7R/dPCOP8BCwykteXuChrWf1P98OSwSl/JXmaqb4ubHxS/Y4oCEVNhesORGF4j/Ky24znIXXKbWVLqWPEtlzFnstJKGVSozQmqjleEmk2lLzc5vmjFhJNdVXYs0ElG@TMeuf@Cw@gJWPD/TK@QQfNwHDuHW@DYWeHzNY@/ddE8WRILj9gc "Ruby – Try It Online")
* Saved 5 bytes thanks to displayname
[Answer]
# Mathematica, ~~110~~ 99 bytes
```
Max@#-Min@#&[#~FromDigits~2&/@Partition[s=Join@@Tuples[{0,1},4][[IntegerDigits@#+1]],Tr[1^s],1,1]]&
```
  
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983scJBWdc3M89BWS1auc6tKD/XJTM9s6S4zkhN3yEgsagksyQzPy@62NYrH6jIIaS0ICe1OLraQMewVsckNjraM68kNT21CKLJQVnbMDZWJ6Qo2jCuOFbHUAfIU/sfUJSZV@KQFm1pbmpkbGJhYGYY@x8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Python 3, 141 bytes
```
def f(a):a=''.join([format(int(i),'#010b')[-4:]for i in str(a)]);b=[int(''.join(a[-i:]+a[:-i]),2)for i in range(len(a))];return max(b)-min(b)
```
[Try it online](https://repl.it/@alaricwhitehead/BCD)
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~96~~ 89 bytes
```
.
@@@$&
@(?=@@[89]|@[4-7]|[2367])
_
T`E`@
\d
_
.
$&$'$`¶
O`
_
@_
+`_@
@__
s`(_+).*\W\1
_
```
[Try it online!](https://tio.run/##K0otycxL/P9fj8vBwUFFjctBw97WwSHawjK2xiHaRNc8tibayNjMPFaTK54rJME1wYErJgXI1ONSUVNRV0k4tI3LPwHId4jn0k6IdwDS8VzFCRrx2pp6WjHhMYZcXPH//xsaAQA "Retina – Try It Online") Somewhat slow, so link only includes a small test case. Edit: Saved 7 bytes thanks to @MartinEnder. Explanation:
```
.
@@@$&
```
Prefix three `@`s to each digit. (These represent the `0`s of the BCD, but are golfier.)
```
@(?=@@[89]|@[4-7]|[2367])
_
```
Change the `@`s to `_`s (representing the `1`s of the BCD) where appropriate.
```
T`E`@
\d
_
```
Fix up the last digit of the BCD.
```
.
$&$'$`¶
```
Generate all of the rotations.
```
O`
```
Sort them into ascending order.
```
_
@_
+`_@
@__
```
Convert them to unary.
```
s`(_+).*\W\1
_
```
Subtract the first from the last number, ignoring intermediate numbers, and convert to decimal.
[Answer]
# [Haskell](https://www.haskell.org/), 130 bytes
```
r=foldl1
f x=max#x-min#x
f#x|s<-show x=r((+).(2*)).r f.take(sum$4<$s).iterate(drop<>take$1)$do d<-s;mapM(pure[0,1])[1..4]!!read[d]
```
[Try it online!](https://tio.run/##RY7Pb4MgHMXv/BXf/jjAOo2otKWzvWw7LFlPOzbNQiK2pgoGaWay7W93oCa7AO@9z3vhKtqbrKq@rBttLLwIK8KjVrrMAQPODgRIb/aFrvKKogK6fS26RRfUpVp0qFh0P20WtFf95RKD8YqEOH4gJDRQhFbcJG7v9TLNli0JSyuNsBLnRjfZwYdLSpa5htwtPNWiOeLmbuQpeqRncqJhmJ5nMyNFfsrPfS1KBXvw1Cc4zn5Y864ghIt2h6eIu6tSyRb2WQYXaZ@1slLZFiHH7Hbw5uRFGggO4Mqlunjfjw7fV7BawdyHc/8aPFyAIgh9B/DaibqpZLtDCADiJPVgQjnzkk6axZRNhpc0GQTfsG1CByPlfB2PnTTh0SYduDhhnKWc8ol2a9toPTaiKOYJZZvtNmYo@O1dhuh4ABqX0TSF/qt/ "Haskell – Try It Online")
## Explanation / Ungolfed
Since we're going to use `foldl1((+).(2*))` to convert from binary to decimal, we might as well not use `maximum` and `minimum` but rather `foldl1 max` (or same with `min` respectively) and use a short `r = foldr1`.
Now, let us define an operator `f#x` which converts `x` to BCD, generates all rotations, reduce these using `f` and convert it to decimal:
```
f # xs
  | s <- show xs
  = foldr1 ((+).(2*))                             -- convert from binary to decimal
  . foldr1 f                                      -- reduce by either max or min
  . take (4 * length s)                           -- only keep 4*length s (ie. all "distinct" rotations)
  . iterate (drop<>take $ 1)                      -- generate infinite list of rotations
  $ do d<-s; mapM (pure[0,1]) [1..4] !! read [d]  -- convert to BCD
```
Now it's only a matter of using this operator once with `max` and once with `min` and subtracting their results:
```
f x = max#x - min#x
```
[Answer]
# PHP, ~~156~~ 153 bytes
```
<?foreach(str_split($argv[1])as$n)$s.=str_pad(decbin($n),4,0,0);for(;$i<$a=strlen($s);)$r[]=bindec(substr($s,$i).substr($s,0,$i++));echo max($r)-min($r);
```
[Try it online!](https://tio.run/##RYzLDoIwFER/xcVd9IZCiuIrhfghhJgCVZpA27Ro/HrrZeVy5pwZP/mU6tvDBa2GicU13KOfzcpAhee7LTtUESxCLJqNeTWyUQ@9sYxaXnHBBUpaMwmmBrVJsyYYUSKEtmtIpQGLr54Q9RwMFv8kKGcZotTD5HaL@jAImC/bf0CZUrqej/tDdRGn8uv8apyNKbc/)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-x`, 20 bytes
```
®¤ùT4Ã¬¬£ZéY ì2Ãn äa
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rqT5VDTDrKyjWulZIOwyw24g5GE=&input=WzksNyw1LDIsMyw0LDgsMCw2LDFdCi14)
Input as an array of digits.
Explanation:
```
®¤                      #Map each digit to base 2
  ùT4Ã                  #Pad each one to 4 places
      ¬                 #Join them to a single binary string
       ¬                #Split them to an array of single characters
        £      Ã        #For each index Y in that array:
         ZéY            # Get the array rotated Y times
             ì2         # Convert the array from binary to decimal
                n       #Sort the results
                  äa    #Get the absolute difference between each element
                        #Implicitly output the sum
```
[Answer]
# Pyth, 24/26 bytes
```
s.+Smi.>Gd2l=Gsm.[\04.Bs
```
Takes input as a quoted string. 26 bytes if it needs to take input as an integer; append `dz` in that case.
[Test Cases (input as strings, 24 bytes)](http://pyth.herokuapp.com/?code=s.%2BSmi.%3EGd2l%3DGsm.%5B%5C04.Bs&input=%22234%22&test_suite=1&test_suite_input=%22234%22%0A%221234%22+%0A%2212%22%0A%22975831%22%0A%224390742%22%0A%229752348061%22&debug=0)
[Test Cases (input as numbers, 26 bytes)](http://pyth.herokuapp.com/?code=s.%2BSmi.%3EGd2l%3DGsm.%5B%5C04.Bsdz&test_suite=1&test_suite_input=234%0A1234+%0A12%0A975831%0A4390742%0A9752348061&debug=0)
[Answer]
# J, 43 bytes
```
3 :'(>./-<./)#.(i.@#|."0 1]),}.#:8,"."0":y'
```
[Try it online!](https://tio.run/##y/r/P03BVk8h2krDTk9f10ZPXzPaSlnPQSNTz0G5Rk/JQMEwFiii41AL5FtZ6CgBhRyUrLhSkzPyFdIUjIxNYExDFDaMZWluChS3MDAz/P8fAA)
Sometimes tacit style makes things difficult. But there's probably a way to do it tacit style that's a lot more concise than this. I think I remember a better way to split a number to digits other than `"."0@":` but I can't seem to recall it...
### Explanation
```
3 :'(>./-<./)#.(i.@#|."0 1]),}.#:8,"."0":y'
                                         y  the input (integer)
                                       ":   convert to string
                                   "."0     evaluate each char (split to digits)
                                 8,         prepend 8
                               #:           debase 2
                             }.             behead (remove the 8)
                            ,               ravel (flatten)
               (i.@#|."0 1])                create a list of rotations
                    |.    ]                   rotate the list
                      "0 1                    for each number on the left
                i.@#                          range 0 ... length - 1
             #.                             convert rotations back to base 10
    (>./-<./)                               max minus min
```
The prepending and removing 8 is to ensure that the right number of zeroes are present (J will reshape its arrays to be the size of their maximum length element, and 8 is 4 digits in binary so it is used).
[Answer]
# APL(NARS), 34 chars, 68 bytes
```
{(⌈/-⌊/)2⊥¨{⍵⌽a}¨⍳≢a←∊⍉(4⍴2)⊤⍎¨⍕⍵}
```
some little test:
```
  h←{(⌈/-⌊/)2⊥¨{⍵⌽a}¨⍳≢a←∊⍉(4⍴2)⊤⍎¨⍕⍵}
  h 9752348061
1002931578825
  h 0
0
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~97~~ ~~91~~ 89 + 2 (`-F`) = ~~99~~ ~~93~~ 91 bytes
```
$a=sprintf"%04b"x@F,@F;@r=sort{$b<=>$a}map{oct"0b".($a=(chop$a).$a)}(@F)x4;say$r[0]-pop@r
```
[Try it online!](https://tio.run/##DcxBDoIwEEDRq0ywJpAIqQorxHTFzhMYF4VUrYFOMx0SDOHqVhZ/@b43NFRRUZNm9e4zBYYnEpAJhtm6FzACTQ7GaWDrBwNsAgewDtAZeGEUugmerONnspdll8yqPai23oYBiRfRXZqr0Ouo/YI9J7JLinQzaf9GL3RWbK2parO5rIP@CrrLR@7RK4rxdC5/6NmiCzG/VYU8ypi3fw "Perl 5 – Try It Online")
]