# Mathematics is fact. Programming is not

In mathematics an exclamation mark ! often means factorial and it comes after the argument.

In programming an exclamation mark ! often means negation and it comes before the argument.

For this challenge we'll only apply these operations to zero and one.

Factorial
0! = 1
1! = 1

Negation
!0 = 1
!1 = 0


Take a string of zero or more !'s, followed by 0 or 1, followed by zero or more !'s (/!*[01]!*/).
For example, the input may be !!!0!!!! or !!!1 or !0!! or 0! or 1.

The !'s before the 0 or 1 are negations and the !'s after are factorials.

Factorial has higher precedence than negation so factorials are always applied first.
For example, !!!0!!!! truly means !!!(0!!!!), or better yet !(!(!((((0!)!)!)!))).

Output the resultant application of all the factorials and negations. The output will always be 0 or 1.

### Test Cases

0 -> 0
1 -> 1
0! -> 1
1! -> 1
!0 -> 1
!1 -> 0
!0! -> 0
!1! -> 0
0!! -> 1
1!! -> 1
!!0 -> 0
!!1 -> 1
!0!! -> 0
!!!1 -> 0
!!!0!!!! -> 0
!!!1!!!! -> 0


The shortest code in bytes wins.

• But 0!=1!, so what's the point of handling multiple factorials? – boboquack Feb 6 '17 at 9:22
• @boboquack Because that's the challenge. – Calvin's Hobbies Feb 6 '17 at 9:24
• <?='1'; ... correct 75% of the time in php. – aslum Feb 6 '17 at 17:17
• I may be wrong here but can't any number with any factorials after it simply be removed and replaced with 1? Like 0!!!! = 1!! = 0!!!!!!!! = 1!!! = 1! = 0! = 1 etc – Albert Renshaw Feb 6 '17 at 22:33
• @AlbertRenshaw That is correct. – Calvin's Hobbies Feb 6 '17 at 22:54

## Mathematica, 25 17 bytes

Input[]/.!x_:>1-x


Takes input from a user prompt. Assumes Mathematica's notebook environment for implicit printing. To make it a command-line script, wrap it in Print[...] or to make it an argumentless function (which then takes input from the prompt), append &.

Mathematica has both of the required operators (with the required precedence), so we can just "eval" the input (which is done automatically by Input[]), but the logical negation operator doesn't work on integers (so it will remain unevaluated). If there's a !x left in the result, we replace it with 1-x.

A couple of fun facts about the evaluation:

1. Mathematica actually also has the double factorial operator !!, which computes n*(n-2)*(n-4)*..., but applied to 0 or 1 it still gives 1, so it doesn't matter that 0!!!!! will actually be parsed as ((0!!)!!)!.
2. Even though Mathematica leaves !0 and !1 unevaluated, it does know that ! is self-inverse, so it will automatically cancel all pairs of leading !. After the ToExpression we're always left with one of 0, 1, !0, !1.
• Since when was a REPL snippet allowed by default? – LegionMammal978 Feb 7 '17 at 12:26
• @LegionMammal978 Apparently since December 2015, but I keep forgetting about it. To be fair, it's not a "snippet" in that it doesn't assume that the input is already stored somewhere in memory. And assuming the notebook environment is then not very different from having a language with implicit output. – Martin Ender Feb 7 '17 at 12:28
• Just curious, could a meta link be provided? (Trying to find information there is stressful, yet another problem of the SE Q&A format...) – LegionMammal978 Feb 8 '17 at 2:04
• @LegionMammal978 it's already in the answer. – Martin Ender Feb 8 '17 at 6:57
• Pure ksh solution x=${x/[01]!*/1};echo$(($x)) - not allowed to post a proper answer :( – DarkHeart Feb 9 '17 at 1:45 # [Bash] + Unix utilities, 21 17 bytes sed s/.!!*$/1/|bc


This must be saved in a file and run as a program. If you try to enter the command directly from the command line, it won't work because !! is expanded due to history substitution being enabled in bash's interactive mode. (Alternatively, you can turn history substitution off with set +H.)

Test case runs:

for x in 0 1 '0!' '1!' '!0' '!1' '!0!' '!1!' '0!!' '1!!' '!!0' '!!1' '!0!!' '!!!1' '!!!0!!!!' '!!!1!!!!'; do ./excl <<<"$x"; done 0 1 1 1 1 0 0 0 1 1 0 1 0 0 0 0  • The old version works, this one doesn't – Cows quack Feb 6 '17 at 9:37 • I used the TIO link – Cows quack Feb 6 '17 at 9:40 • @KritixiLithos It worked fine when I tried it on my Linux box. The problem was apparently that TIO requires a newline at the end of the simulated input line. It's a confusing situation, so I took out the TIO link. If you want to try it out there, here's the link again (but be sure to include a newline at the end of the input if you change the input to test it out): tio.run/nexus/bash#@1@cmqJQrK@nqKilom@oX5OU/P@/… – Mitchell Spector Feb 6 '17 at 9:53 • But what if someone has run mkdir -p 's/.!!'{bunch,of,different,directories}\$/1? Then you'll get Pathname Expansion and Sed will be attempting to read directories as though they were files, instead of reading standard input, and it won't output anything! :) – Wildcard Feb 7 '17 at 9:13
• @Wildcard I agree completely. In production scripts, I always use quotes in situations like this. (In this case, I would actually put double-quotes around the argument to sed, rather than just escaping the *. It's easier to read than using backslashes, and it avoids the possibility of missing some special character.) – Mitchell Spector Feb 7 '17 at 9:32

## Retina, 2015 14 bytes

Thanks to Leo for saving 1 byte.

0!
1
!!

^1|!0


Try it online!

### Explanation

0!
1


Turn 0! into 1. We don't care about any other trailing !s, the resulting number is the same as if we had applied all factorials.

!!



Cancel pairs of negations. This may also cancel some factorials, but that's irrelevant.

^1|!0


Count the number of matches of this regex, which is either 1 or 0 and gives the desired result.

• Alternate solution for same bytecount: \d.+... – Cows quack Feb 6 '17 at 9:15
• @KritixiLithos Found a way to avoid that altogether. – Martin Ender Feb 6 '17 at 10:07
• You can remove the ^ before !0 – Leo Feb 6 '17 at 12:53

## Grime, 14 12 9 bytes

e\0!~\!_


Try it online!

## Explanation

This matches the input against a pattern, printing 1 for match and 0 for no match.

e\0!~\!_
e         Match entire input against this pattern:
!      not
\0       a sole 0
~     xor
\!   exclamation mark
_  followed by this pattern matched recursively.


The idea is this. If the input begins with a digit, then the recursive part \!_ always fails, and \0! succeeds unless we have a single 0. Their xor succeeds unless the input is a single 0. If the input begins with a !, then \0! always succeeds, and \!_ succeeds if the recursive match succeeds. Their xor succeeds exactly when the recursive match fails, thus negating it.

# Brainfuck, 85 72 (84) bytes

,[>-[-----<->]<++[>++++[-<++++>]+<[[+],[[-]>-<]]]>[<<+[-->]>[<],>-]<]<+.


to return numerically, or

,[>-[-----<->]<++[>++++[-<++++>]+<[[+],[[-]>-<]]]>[<<+[-->]>[<],>-]<]-[-----<+>]<--.


for ASCII text. > may also be prefixed to avoid memory wrapping.

Try it online!

Loops over the input.
On 1, ends.
On "!", toggles bool a stored as 0 or 255.
On "0", toggles if there is no trailing bit, then ends.

Memory labels  | BOOL | INPUT | FLAG |

,                   first input
[                     # loop on INPUT
>-[-----<->]<++     subtract 49 == "1"

[                     # case not "1"
>++++[-<++++>]      add 16 since 49 take 16 == "!"

+                   set FLAG
<                   move to INPUT
[                     # case "0"
[+],                clear and new INPUT
[                     # case "0!"
[-]>-<              clear INPUT and FLAG
]
]
]

>                   move to FLAG
[                     # case "!" or "0" without tail
<<+[-->]>[<]        not the BOOL
,                   take new input
>-                  clear FLAG
]
<                   move to INPUT
]

+.                    return 0 or 1


Or for text response, replace the last line with

-[-----<+>]<--.       add 49 for "0" or "1" conversion and return


# Brainfuck - way to many bytes (232 bytes)

Clearly the wrong language for winning in code golf. Mainly I noticed a lack of anyone using this esolang. There is a good online interpreter bf interpeter or you can actually watch what the program does using this bf visualizer.

>>>>>,[>+++[<---------------->-]<<<<<<[-]+>[-]>>>>[-[<<[>+<<<<->>>[<<+>>-] ]<<[>>+<<-]<[>>+<<[-]]>>>>>[-]]<<<<<[>>>++<<<-]>+>>>>[-]]<<<<-[>>+<<[-]]>>>>,]<<->[<[-]+>[-]]<<[<[-]>>[<<+>>[-]]+<<[->>-<<]>-]>>[-]+++[<++++++++++++++++>-]<.

• You crazy man!! – Almo Feb 8 '17 at 23:20
• Love it, can you do that in malbolge? XD – Stefan Nolde Feb 10 '17 at 4:36
• Information: There are too much shorter solutions below. – user202729 Apr 21 '18 at 7:04

# Python, -44- 42 bytes

Saved 2 bytes thanks to Zgarb!

lambda x:(x[-1]=='0')^len(x.rstrip('!'))%2


Step by step:

1. x[-1]!='0'
if x ends with 1 or !x doesn't end with 0, the factorial portion must have value 1, else 0
2. ^len(x.rstrip('!'))%2
exploit xor's property as a "conditional not". The condition in this case is if the length of initial !s is odd. However, .rstrip doesn't remove the number from the string so the length calculated is offset by 1, therefore the condition is inverted
3. The offset by 1 in step 2 is corrected by changing != to == in step 1. Zgarb suggested using a difference comparison operator rather than applying another inversion, saving 2 bytes.

Try it online!

• Fails on an input of !!0; it is currently returning 1. – Value Ink Feb 6 '17 at 9:45
• @ValueInk should be working now – busukxuan Feb 6 '17 at 9:55
• lambda x:(x[-1]=='0')^len(x.rstrip('!'))%2 avoids the extra inversion. – Zgarb Feb 6 '17 at 11:18
• crossed out 44 is still regular 44 – Rɪᴋᴇʀ Feb 6 '17 at 15:23
• I think he's stating that a crossed out 44 in the font used doesn't look crossed out... :) The cross out portion overlaps with the horizontal portion of the 4s. – JeffC Feb 9 '17 at 16:12

## JavaScript (ES6), 4341 29 bytes

s=>+eval(s.replace(/.!+$/,1))  ### Non-regex method (41 31 bytes) Below is my initial approach. It's slightly more interesting, but significantly longer still a bit longer even after a significant optimization by Neil (10 bytes saved). f=([c,...s])=>1/c?c|s>'':1-f(s)  ### Test cases let f = s=>+eval(s.replace(/.!+$/,1))

;[
"0", "1", "0!", "1!", "!0", "!1", "!0!", "!1!", "0!!",
"1!!", "!!0", "!!1", "!0!!", "!!!1", "!!!0!!!!", "!!!1!!!!"
].map(
s => console.log(s, '=>', f(s))
)

• I can only save 10 bytes from your non-regex method, so it's still too long: f=([c,...s])=>1/c?c|s>'':1-f(s). – Neil Feb 6 '17 at 13:41
• @Neil Since it's much better than my 1st attempt anyway, I took the liberty to include your suggestion. – Arnauld Feb 6 '17 at 14:19
• Ha, I had the same idea but you golfed it better. :) – Devsman Feb 8 '17 at 15:23

# Jelly, 5 bytes

VeMḂ$ Try it online! Monadic function expecting a string. Inputs with leading !s cause a 1 to be printed to STDOUT along the way, so the TIO link I give is a test harness that prints the input-output pairs beneath the first line of output. ### How? VeMḂ$ - Monadic link: string
V     - eval the string
- the implicit input of 0 causes !...! to evaluate to 1 (which gets printed),
- the result is the evaluation of the rest: "0"=0; "0!"=1; "1"=1; "1!"=1; ...
e    - exists in?
$- last two links as a monad: M - Maximal indexes - the "0" and "1" characters are greater than "!", - so this results in a list of one item [i] where - i is the 1-based index of the 0 or 1 character. Ḃ - %2 (vectorises) - [i%2], so a 0 if we need to logically negate and a 1 if not - hence we check equality with e rather than inequality.  # 05AB1E, 9 bytes Code: .V¹'!ÜgG_  Uses the CP-1252 encoding. Try it online! or Verify all test cases! Explanation: .V # Evaluate the input as 05AB1E code. This computes the factorial part. '!Ü # Remove trailing exclamation marks.. ¹ # ..from the first input g # Get the length of the resulting string G # Do the following length - 1 times: _ # Negate the number  # Retina, 13 bytes A somewhat weird approach, but it's short and it works. 0$
!1
!!

^\d


With the first two lines we replace an ending 0 with !1: with this replacement we now know that the part of our string from the digit onwards is equal to 1.

Next two lines, remove pairs of !: double negation erases itself, and we already accounted for factorial with the previous step.

Last line, match a digit at the start of the string and return the number of matches: if the negations have all been eliminated we'll find a match (and as we said before we know this is equal to 1), if there's still a negation this won't match.

Try it online!

• Wouldn't the final digit necessarily always be a 1? In that case, you could use 1 rather than \d. – user62131 Feb 6 '17 at 22:39
• @ais523 no, because the first part will only replace an ending 0, so for example the input 0! will stay unchanged until the last line – Leo Feb 6 '17 at 23:07
• Really lovely solution, nice work! :) – Martin Ender Feb 6 '17 at 23:32

# Ruby, 12+1 = 392415 13 bytes

Uses the -n flag. Thanks to @GB for -9 bytes!

p~/!*$|0$/%2

• Since you only check the length, you can delete the trailing zero, instead of checking "!0" first and a single zero after that. – G B Feb 7 '17 at 8:10
• @GB that's a wonderful idea! However, I found a solution that's even shorter by modifying my regex to look for the position of 0 or end-of-line – Value Ink Feb 7 '17 at 9:25
• Then you could just check for trailing '!' or zero or end of line: p~/!+$|0$|$/%2 is just 14 bytes. – G B Feb 7 '17 at 9:39 • And then "0$|$" could become "0?$" to save another byte. – G B Feb 7 '17 at 14:51
• Better yet !*$ is shorter by two! – Value Ink Feb 7 '17 at 18:03 # Perl, 20 bytes 19 bytes of code + -p flag. s/\d!+/1/;$_=0+eval


Try it online!

Perl's negation returns undef or 1, so I use 0+ to numerify the result 0+undef returns 0. Besides that, not much to say about the code.

• Just wrote exactly this. Have a +1. – primo Feb 7 '17 at 9:26
• @primo Glad to see that for once I'm not 20 bytes behind you! Thanks :) – Dada Feb 7 '17 at 9:59

# C, 686261 53 bytes

c;e(char*a){for(c=1;*a<34;a++)c^=1;c=a[1]?c:*a&1^!c;}


Squeezed out a few more bytes with some abuse

Try it online!

• I think you can remove the int from the function and you can change the *a==33 to *a<34. – Cows quack Feb 6 '17 at 18:18
• Alas *a%2 is shorter than *a-48 – Cows quack Feb 6 '17 at 18:22
• Thanks for the tip. I was also able to eliminate another character by removing the brackets around the return and assigning it. – Ahemone Feb 6 '17 at 22:30
• I am pretty sure for(;*a<34;a++) can be shortened to for(;*a++<34;) saving 1 byte – Albert Renshaw Feb 6 '17 at 22:34
• Unfortunately not, as the conditional statement it will always execute and so will push the pointer too far ahead for the return dereference. – Ahemone Feb 6 '17 at 22:40

# Perl 6, 3228 23 bytes

{m/(\!)*(1|0.)*/.sum%2}


### How it works

{                     }  # A lambda.
{m/            /      }  # Match the lambda argument against the regex:
(\!)*                 #   Zero or more !.
#     (First capture will be an array with one element per negation).
(1|0.)*          #   A 1, or a 0 and another character, zero or more times.
#     (Second capture will be a one-element array if the factorial
#     part evaluates to 1, and an empty array otherwise.)
.sum     # Add the lengths of the two captures,
%2   # and return that sum modulo 2.


f('!':b)="10"!!read[f b]
f[a]=a
f _='1'


Defines a function f, which takes a string and returns a character. Try it online!

## Explanation

There are three cases: input begins with !, input has length 1, and everything else.

f('!':b)=    -- If input has head '!' and tail b,
"10"!!      -- we index into the string "10"
read[f b]  -- using f b converted to int. This essentially inverts f b.
f[a]=        -- If input has only one character, we know it's a digit,
a           -- so we can just return it.
f _=         -- In all other cases, we know the input is a digit followed by !s,
'1'         -- so we can return '1'.

• Switch from String to Integer as the return type: f('!':b)=[1,0]!!f b;f"0"=0;f _=1. – nimi Feb 6 '17 at 20:24

# Befunge, 24 bytes

~"!"-:#v_$1+ *+2%!.@>0~  Try it online! This starts by counting the number of ! characters read from stdin. The first character that isn't a ! will either be a 0 or 1, but in the process of testing for ! we will have subtracted 33, making it either 15 or 16. We then read one more character, that will either be an ! or EOF, and compare if that is less than 0 (i.e. EOF). Taking those three data points - the exclamation count (c), the digit value, (d), and the end-of-file condition (e) - we can calculate the result as follows: !((c + d*e) % 2)  Multiplying the digit value by the end-of-file condition means it will be converted to zero if the digit was followed by a !, thus giving it the same modulo 2 value as a 1 (which remember has been converted to 16). But before applying the modulo 2, we add the initial exclamation count, which effectively toggles the modulo 2 result as many times as their were ! prefixes. And finally we not the result since our baseline values for 0 and 1 are the opposite of what we need. Looking at the code in more detail: ~ Read a character from stdin. "!"- Subtract 33 (ASCII for '!'). : _ Make a duplicate and check if zero (i.e. is it a '!').$1+     If so, drop the duplicate, increment a counter, and repeat.
v         Otherwise move to the second line, leaving the digit value on the stack.
>0~      Read one more character and check if less than 0 (i.e. EOF).
*                Multiple by the digit value, making it zero if not followed by EOF.
+               Add to the exclamation count.
2%             Modulo 2 the result.
!            Then not that value.
.@          And finally write to stdout and exit.


f('!':b)=1-f b
f"0"=0
f _=1


Try it online!

Each leading ! complements the output for the rest of the expression, done as 1-. We keep flipping until we hit a digit. If the remaining is just "0", the result is 0. Otherwise, it's a 1 or is followed by one or more !, so the result is 1.

## Ruby, 22 21 20 bytes

->s{(s=~/!*$|0$/)%2}


Explanation:

• First case, I got some '!' at the end, remove them, get length modulo 2.
• Second case, no '!', if last character is zero then remove it, get length modulo 2
• If the last character is 1, back to the first case

(-1 byte stealing @Value Ink's idea)

• Awesome, I looked at this puzzle for 10 minutes but had not much time and then forgot about it. Now spotted it again in active questions and was delighted to see such a nice approach. – akostadinov Feb 13 '17 at 7:54

# Jelly, 8 bytes

œr”!LḂ=V


Try it online!

This is a function (monadic link) that takes one argument and returns via its return value. (It also often writes junk to standard output as a side effect, but we don't care about that.)

## Explanation

œr”!LḂ=V
œr”!      Take {the input}, with all trailing ! deleted
L     Take the length of this
Ḃ    Take the parity of that length
=   Return 0 if unequal, 1 if equal to:
V    the value of {the input} when eval'ed as a niladic Jelly program


First, note that as the input always consists of some number of !, followed by a digit, followed by more !, that if we delete the trailing ! and take the length, we'll end up with one plus the number of leading ! in the program. Taking the parity of this will return 0 if there were an odd number of !, or 1 if there were an even number of !. Comparing to 0 is a "not" function, whereas comparing to 1 is the identity function; thus œr”!LḂ= effectively implements the "treat leading ! as NOT operators" part of the question.

As for the second half, handling factorials, ! is a factorial operation in Jelly, so if the program has no leading !, we can solve the problem directly with a simple eval (V). If the program does have leading !, those will be interpreted as taking the factorial of 0 (possibly multiple times), producing a return value of 1, which will be printed to standard output and discarded once a digit is seen; thus, they have no impact on the return value of the function that's my submission to the question.

• Very nice and great explanation. – ElPedro Feb 6 '17 at 21:48

# Python, 38 bytes

lambda s:(s[1::2]>s[::2])^ord(s[-1])%2


TryItOnline!

An unnamed function taking an input string s and returning an integer 0 or 1.

s[1::2] is a slice of the input string that starts at index 1 and has a step size of two:
'Like this' -> 'ieti'

s[::2] is similar but starts at the default index of 0:
'Like this' -> 'Lk hs'

The test (s[1::2]>s[::2]) checks if the 0-based index of the '0' or '1' is odd, i.e. if we need to complement.
This works because the ordering of strings is checked lexicographically with any non-empty string greater than the empty string, and with ASCII ordering, so '1'>'0'>'!'. This is a byte shorter than the simpler s.index(max(s))%2.

The ord(s[-1])%2 checks to see if the last character is not a '0' (for valid input), and results in an integer (whereas the same length (s[-1]!='0') would return a boolean).
This works because the last character of the input, s[-1], will be a '0', '1', or '!' which have ASCII code points 48, 49, and 33 respectively, which are 0, 1, and 1 modulo 2.

The ^ then performs a bitwise exclusive or operation on the two above values, returning an integer since one input, the right one, is an integer. If the left is True the complement of the right is returned, if the left is False the right is returned, as required.

# Java 7, 10582 81 bytes

int a(char[]a){int b=0,c=0;for(;a[b++]<34;c^=1);return(b<a.length?1:a[b-1]&1)^c;}


Try it online!

### Old regex-ish solution

int a(String a){a=a.replace("0!","1").replaceAll("1.*","1");int b=a.length()-1;return b%2^a.charAt(b)&1;}

• c^=1 is super clever. That's an unused operator if ever I've seen one. – Addison Crump Feb 9 '17 at 8:19

## CJam, 12 11 bytes

r_W='0=!\~;


Try it online! Test suite (prints a 1 for each correct test case).

r      e# Read input.
_W='0= e# Duplicate and check whether the string ends in '0'. This is the
e# only case in which the factorial part results in 0.
!      e# Negate this to get the actual result of the factorial part.
\      e# Swap with the input.
~      e# Evalute the input as CJam code. The leading ! will apply the logical
e# negations to the factorial result. The 0 or 1 will then push a junk value
e# which is potentially negated a few times as well, by the factorials.
;      e# Discard the junk value.


f s|foldr(\_->not)(last selem"1!")$fst.span(<'0')$s="1"|1<3="0"


Try it online! Usage: f "!!!0!!!!"

Saved two bytes thanks to @nimi.

# Brainfuck, 115 bytes

>,[->++++[<-------->-]<[--------------->,[<[-]+>-]<<[->-[>+<+]>[-<+>]<<]>>++++++[-<++++++++>]<.>>+<]>-[<<+>,>[-]]<]


Try it online!

## Ungolfed:

% 0: inverter count
% 1: result
% 2: if/else flag; tmpspace in inner loop 0

>1,[
->2++++[<-------->-]<1 subtract 33 (!)
[
% we've reached the number
---------------
% now it's either 0 or 1

% check next char; If it's not 0 then it's '!'
% 0! = 1! = 1!...! so we only need to determine if at least one ! exists
>2,
[<[-]+>-]<1

% apply inversions
<0
[->1
% invert cell 1 once each iteration
% cell 1 is 0 or 1
-          % cell 1 is 255 or 1
[>+<+]     % cell 1 is 0; cell 2 is 1 iff cell 1 should be 1
>2[-<+>]<1 % cell 1 is 1 or 0
<0]

% print result
>1>++++++[-<++++++++>]<1.

>>2+< % tape={0 r 0 1}
]
>2-[ % we haven't seen the number yet
<<0+>1,>2 % add to inverter count
[-]
]<1
]


## Batch, 62 bytes

@set/ps=
@set s=%s:0!=1%
@set s=%s:!!=%
@cmd/cset/a%s:1!=1%


Takes input on STDIN. Batch actually understands leading !s correctly for this challenge, but the trailing !s need to be dealt with, which takes three steps:

• Change 0! to 1
• Delete pairs of !! (this is safe for the !!s before the digit too)
• Delete any remaining trailing ! (which by now can only be after a 1)

# IBM/Lotus Notes Formula - 77 bytes

@Eval(@Left(a;@If(@Like(a;"%1%");"1";"0"))+@If(@Ends(a;"!");"1";@Right(a;1)))


There is no TIO for Notes Formula so a screenshot of all test cases is shown below:

How it works

@Eval() evaluates a string as an expression

First we check if the input string in field (input) a contains 1 or 0 and take all characters to the left of whichever it is which will be a string of ! characters. We don't care how many. @Eval() will take care of that.

Next we look to see if there is a ! at the end of the string. If there is we append 1 to the ! string (0! and 1! are both 1 - it doesn't matter how many ! characters there are at the end) otherwise we append the last character unchanged because it is not a ! and could be either a 1 or a 0.

We now have a string containing the leading inversions plus a number defined by whether there are any factorial characters so we can feed this to @Eval() and get the results above.

# sed, 3633 31 bytes

Pure sed, no bc / shell utils. Works on GNU sed < 4.3; 33 bytes on BSD and GNU 4.3+.

s/.!!*$/1/ : s/!0/1/ s/!1/0/ t  Straightforward enough if you're familiar with sed; commented for those who aren't: # Since 0! == 1! == 1 and factorial has precedence, just collapse any trailing "!" s/.!!*$/1/
# Define an anonymous label
:
# Invert 0 if needed
s/!0/1/
# Invert 1 if needed
s/!1/0/
# If a change was made, go back to the anonymous label.
t


Test:

% cat 109248.sed
s/.!!*$/1/ :l s/!0/1/ s/!1/0/ tl % wc -c 109248.sed 33 109248.sed % cat cases 0 1 0! 1! !0 !1 !0! !1! 0!! 1!! !!0 !!1 !0!! !!!1 !!!0!!!! !!!1!!!! % sed -f 109248.sed cases 0 1 1 1 1 0 0 0 1 1 0 1 0 0 0 0 % gsed -f 109248.sed cases 0 1 1 1 1 0 0 0 1 1 0 1 0 0 0 0 %  • IIRC some (all?) versions of sed allow you to use the null string as a label name. If you can get that to work here, it'd save you two bytes. Actually, I'm not sure the label is even needed; unless I've missed something, the first line is idempotent, so you might be able to jump back to the start of the program rather than needing a label. – user62131 Feb 13 '17 at 5:04 • @ais523 I thought so too, but evidently it doesn't work in BSD versions. The man page says "If no label is specified, branch to the end of the script," and even that wasn't working when I tried. – Kevin Feb 13 '17 at 9:05 • GNU sed does allow a label to be just : (more of a bug taken as feature), in which case both the t and b! commands jump to the position of the label. Plus, a sed code must work for at least one version of sed, similar to other languages, so you don't need to create code that works for BSD as well. – seshoumara Feb 17 '17 at 17:31 # PHP 7.1, 58555437 35 bytes Note: uses IBM-850 encoding echo!!$argn[-1]^strspn($argn,~Ì)%2;  Run like this: echo '!!!0!!!!' | php -nR 'echo!!$argn[-1]^strspn($argn,~Ì)%2;';echo > 0  # Explanation echo strspn($a=$argv[1],~Ì) # Count the number of leading exclamation marks. % 2 # Make 0 (even) or 1 (odd). ^ !!$a[-1];            # Negate with factorial part (truthy value of the
# last char):
# - "0" is considered falsy.
# - "1" or "!" is considered truthy.


# Tweaks

• Saved 3 bytes by using IBM-850 encoding
• Saved a byte by changing the regex slightly
• Saved 17 bytes, new version without long function names and return
• Saved 2 bytes by using -R (which makes $argn available) # Bean, 24 bytes Hexdump: 00000000 26 4a c1 53 a0 17 53 d0 80 a0 5d 20 80 0a a1 80 &JÁS .SÐ. ] ..¡. 00000010 81 00 25 3a ae a1 ab 24 ..%:®¡«$
00000018


Equivalent JavaScript:

+eval(a.replace(/.!+\$/,1))


Sorry for stepping on your toes, Arnauld.

### Explanation:

Takes first line of input as unformatted string in a, and replaces any digit followed by one or more ! with 1, so that the rest can be eval`'d by JavaScript.

## protected by Community♦Apr 21 '18 at 6:59

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).