[Question]
      [
Given an integer greater than 1, output the number of ways it can be expressed as the sum of one or more consecutive primes.
Order of summands doesn't matter. A sum can consist of a single number (so the output for any prime will be at least 1.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Standard rules apply.
See [this OEIS wiki](http://oeis.org/wiki/Representations_as_the_sum_of_one_or_more_consecutive_primes) for related information and sequences, including the sequence itself [OEIS A054845](http://oeis.org/A054845).
### Test cases
```
2 => 1
3 => 1
4 => 0
5 => 2
6 => 0
7 => 1
8 => 1
10 => 1
36 => 2
41 => 3
42 => 1
43 => 1
44 => 0
311 => 5
1151 => 4
34421 => 6
```

[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to dylnan
```
ÆRẆ§ċ
```
A monadic link
**[Try it online!](https://tio.run/##y0rNyan8//9wW9DDXW2Hlh/p/v//v7GhIQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9wW9DDXW2Hlh/p/n90z@H2R01r3P//N9Ix1jHRMdUx0zHXsdAxNNAxNtMxMdQxMdIxAUqY6BgbGuoYGpoaAgA "Jelly – Try It Online") (note the final test case would time out at 60s at TIO).
### How?
```
ÆRẆ§ċ - Link: integer, n
ÆR    - primes from 2 to n inclusive
  Ẇ   - all contiguous substrings
   §  - sum each
    ċ - count occurrences of n
```
[Answer]
# [R](https://www.r-project.org/), 95 bytes
```
function(x,P=2){for(i in 2:x)P=c(P,i[all(i%%P)])
for(i in 1:x){F=F+sum(cumsum(P)==x)
P[i]=0}
F}
```
[Try it online!](https://tio.run/##Tc1PC4MgGAbwu59CkMCXNcg/tTHw2tl7dIhAEJqNWiyIPrvTsUgv8vN9n8fJj6@3Hd1MP93k1JUBMsqbxfXxla65Vhw2M07UYuswf6ygVU91bptuGKjNMg1tyBwLLCxstaov8/Kk/fKMlwalVkC6sa0qdlTv3lAOOB6CGTJUpJAHioDyAA@o0sktzdxTsAKS6grOAsn@EBE8WZMihYTzH8F@IYLLWM3KKIJlnEjJgwiu/Bc "R – Try It Online")
* -24 bytes thanks to @Giuseppe who has basically revolutionized my solution supporting 34421 as well !
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
### Code
```
ÅPŒOQO
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##yy9OTMpM/f//cGvA0Un@gf7//5sYAgA "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), 92 bytes
```
n=>(a=[],k=1,g=s=>k>n?0:!s+g(s>0?s-(p=d=>k%--d?p(d):d<2&&a.push(k)&&k)(++k):s+a.shift()))(n)
```
[Try it online!](https://tio.run/##dc/NDoIwDAfwu0@hB0kbPmQw1BAHD2I8LA5QRwax6usjaoJxcT32l7b/XuRD0vF67m@h6VQ11GIwogAp9odACxY0gkShC1PG@YL8BqiISwqhF2psL8NQlT0ozNUu8TwZ9Xc6gUbP0wi@rzEnX0Z0Otc3QEQwOBw7Q11bRW3XQA0J4vxVq9WczX4pdRP/UmxR9qXEorV7auO@tXUTiz/2L/x6IjsGZxOlNiXOhTx1E5/I/itln2MjZXZ4lr1tJD48AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
n => (                          // n = input
  a = [],                       // a[] = array holding the list of consecutive primes
  k = 1,                        // k = current number to test
  g = s =>                      // g = recursive function taking s = n - sum(a)
    k > n ?                     //   if k is greater than n:
      0                         //     stop recursion
    :                           //   else:
      !s +                      //     increment the final result if s = 0
      g(                        //     add the result of a recursive call to g():
        s > 0 ?                 //       if s is positive:
          s - (                 //         subtract from s the result of p():
            p = d => k % --d ?  //           p() = recursive helper function looking
              p(d)              //                 for the highest divisor d of k,
            :                   //                 starting with d = k - 1
              d < 2 &&          //           if d is less than 2 (i.e. k is prime):
              a.push(k) &&      //             append k to a[]
              k                 //             and return k (else: return false)
          )(++k)                //         increment k and call p(k)
        :                       //       else:
          s + a.shift()         //         remove the first entry from a[]
                                //         and add it to s
      )                         //     end of recursive call
  )(n)                          // initial call to g() with s = n
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~14~~ 9 bytes
```
{⟦ṗˢs+?}ᶜ
```
[Try it online!](https://tio.run/##ASIA3f9icmFjaHlsb2cy//974p@m4bmXy6JzKz994bac//8zNv9a "Brachylog – Try It Online")
[Multiple test cases](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp0A5M5f9nDn9NOLirWt7W1rH26b8/9/tJGOgrGOgomOgqmOgpmOgrmOgoWOgqEBUBTIMzEEYqAKE5ASoBpjQ6CAoaGpYSwA "Brachylog – Try It Online")
*(-5 whole bytes, thanks to @Kroppeb!)*
### Explanation:
```
{⟦ṗˢs+?}ᶜ
{      }ᶜ     Count the number of ways this predicate can succeed:
 ⟦            Range from 0 to input
  ṗˢ          Select only the prime numbers
    s         The list of prime numbers has a substring (contiguous subset)
     +        Whose sum
      ?       Is the input
```
[Answer]
# MATL, ~~15~~ 12 bytes
```
EZqPYTRYsG=z
```
[Try it on MATL Online](https://matl.io/?code=EZqPYTRYsG%3Dz&inputs=1151&version=20.9.2)
The initial `E` (multiply by 2) makes sure that, for prime input, the result of the later `Ys` (`cumsum`) does not have the input prime repeating itself in the zeroed part of the matrix (thus messing with the count).
### Explanation:
```
                % Implicit input, say 5
E               % Double the input
 Zq             % Get list of primes upto (and including) that
                %  Stack: [2 3 5 7]
   P            % Reverse that list
    YT          % Toeplitz matrix of that
                %  Stack: [7 5 3 2
                           5 7 5 3
                           3 5 7 5
                           2 3 5 7]
      R         % `triu` - upper triangular portion of matrix
                %  Stack: [7 5 3 2
                           0 7 5 3
                           0 0 7 5
                           0 0 0 7]
       Ys       % Cumulative sum along each column
                %  Stack: [7  5  3  2
                           7 12  8  5
                           7 12 15 10
                           7 12 15 17]
         G=     % Compare against input - 1s where equal, 0s where not
           z    % Count the number of non-zeros
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes
```
.+
$*_$&$*
_
$`__¶
A`^(__+)\1+$
m)&`^((_)|¶)+¶[_¶]*(?<-2>1)+$(?(2)1)
```
[Try it online!](https://tio.run/##Dcq7DQIxEEXR/NUxrGZsgRjbLASIFRFF8BkTEBCwwYqQulyAGzMOr85dXt/3/Gwr5ktuGw9yRgM5GCib1YJzfrCZl5t6wkeGnmzyq0V8Ldd@3B1Px3U4qXjiiYOotBYQkbDDiD0O0C3iiKRIAalDQlT9Aw "Retina 0.8.2 – Try It Online") Link includes faster test cases. Explanation:
```
m)
```
Run the whole script in multiline mode where `^` and `$` match on every line.
```
.+
$*_$&$*
```
Convert to unary twice, first using `_`s, then using `1`s.
```
_
$`__¶
```
Generate all the prefixes of the `_`s and add two to each, thus counting from \$2\$ to \$n + 1\$.
```
A`^(__+)\1+$
```
Delete all the composite numbers in the range.
```
&`^((_)|¶)+¶[_¶]*(?<-2>1)+$(?(2)1)
```
Match any number of `_`s and newlines (starting and ending at the end of a line) then compare the number of `_`s with the number of `1`s. Count the number of sums of consecutive prime numbers which add up to \$n\$.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes
-1 byte thanks to [Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (use named argument `¹` instead of `S`)!
```
#¹ṁ∫ṫ↑İp
```
[Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpGBrp6CkUfyoqbFI89C2/8qHdj7c2fioY/XDnasftU08sqHg////RlzGXCZcplxmXOZcFlyGBlzGZlwmhlwmRlwmQAkTLmNDQy5DQ1NDAA "Husk – Try It Online")
### Explanation
```
#¹ṁ∫ṫ↑İp  -- example input: 3
#¹        -- count the occurrences of 3 in
      İp  -- | primes: [2,3,5,7..]
     ↑    -- | take 3: [2,3,5]
    ṫ     -- | tails: [[2,3,5],[3,5],[5]]
  ṁ       -- | map and flatten
   ∫      -- | | cumulative sums
          -- | : [2,5,10,3,8,5]
          -- : 1
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
:"GZq@:g2&Y+G=vs
```
[Try it at MATL Online!](https://matl.io/?code=%3A%22GZq%40%3Ag2%26Y%2BG%3Dvs&inputs=311&version=20.9.2)
### Explanation
```
:"        % Input (implicit): n. For each k in [1 2 ... n]
  G       %   Push n
  Zq      %   Primes up to that
  @:g     %   Push vector of k ones
  2&Y+    %   Convolution, removing the edges
  G=      %   True for entries that equal n
  v       %   Concatenate vertically with previous results
  s       %   Sum
          % End (implicit). Display (implicit)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~106~~ 104 bytes
```
P=k=o=1
p=[]
i=input()
exec'o+=P%k*sum(p)==i;P*=k*k;k+=1;p+=P%k*[k];exec"p=p[i<sum(p):];"*k;'*i
print~-o
```
[Try it online!](https://tio.run/##JY4xa8MwFIT3@xVCUJI4FPpsJS1R35iu9dDNeGhcQYRa66HKtFn6110LT3dwH3cnt3yNYz0P8cOx1npuOXBkgnDXw7MfZcrbHdyvGzZxz@1dqL6nr63smL1tKw5VsGHPZGUNu9DbAmth6fzzyp56qxduU3lI8mP@u4/zMgb8XP2nU29pcicoldOtiFKlQJVLKH5wktX59eWcUkwrcEnuPcw1GhgccMQjnkAPaI4wBFPDLIFBQwSiA/0D "Python 2 – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~100~~ 98 bytes
```
import StdEnv,StdLib
$n=sum[1\\z<-inits[i\\i<-[2..n]|all(\j=i/j*j<i)[2..i-1]],s<-tails z|sum s==n]
```
[Try it online!](https://tio.run/##RY6xDoIwFEV3vqKJDGooBmRsNx1M2BgpQy1gHmkfhrYmEr7dimFwujn3JDdX6U5iMGPrdUeMBAxgnuPkSOXaK76SNUq4RzFy602dCTEzCgjO1iAEMFrnaYrNIrXei4HDaTgODA6/FmjWNIll1EnQlszLOkAs59iEysnJRTvSe1QORiScxCuiN/duWuFcFHkW8b/fTPioXsuHDfRWhssbpQG1wfbyCw "Clean – Try It Online")
Defines the function `$ :: Int -> Int` which works as explained below:
```
$ n                              // the function $ of n is
    = sum [                      // the sum of
        1                        // 1, for every
        \\ z <- inits [          // prefix z of
            i                    // i, for every
            \\ i <- [2..n]       // integer i between 2 and n
            | and [              // where every
                i/j*j < i        // j does not divide i
                \\ j <- [2..i-1] // for every j between 2 and i-1
            ]
        ]
        , s <- tails z           // ... and suffix s of the prefix z
        | sum s == n             // where the sum of the suffix is equal to n
    ]
```
(Explanation is for an older but logically identical version)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 53 bytes
```
{+grep $_,map {|[\+] $_},[\R,] grep *.is-prime,2..$_}
```
[Try it online!](https://tio.run/##HcmxDoIwFAXQX7kDMQK18bWP6qB8hCsQwtAaEhqbMhH022vDeHKCjYtJfsPJ4Zn2@h1tQDEKPwXs366vh6yf6PqXGHBkJef1EuLsrVBS5kzrtMGdi7GE@0Q8FDQYDQxuuIOu0AZMYAXOwdBEIGqoTX8 "Perl 6 – Try It Online")
Uses the triangle reduction operator twice. The last test case is too slow for TIO.
### Explanation
```
{                                                   } # Anonymous block
                               grep *.is-prime,2..$_  # List of primes up to n
                         [\R,]  # All sublists (2) (3 2) (5 3 2) (7 5 3 2) ...
          map {|[\+] $_},  # Partial sums for each, flattened
 +grep $_,  # Count number of occurrences
```
[Answer]
# Japt, 17 bytes
There's gotta be a shorter way than this!
Craps out on the last test case.
```
õ fj x@ZãYÄ x@¶Xx
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9SBmaiB4QFrjWcQgeEC2WHg=&input=MTE1MQ==) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=9SBmaiB4QFrjWcQgeEC2WHg=&input=WwoyCjMKNAo1CjYKNwo4CjEwCjM2CjQxCjQyCjQzCjQ0CjMxMQoxMTUxCl0tbVI=)
---
## Explanation
```
                      :Implicit input of integer U
õ                     :Range [1,U]
  fj                  :Filter primes
      @               :Map each integer at 0-based index Y in array Z
         YÄ           :  Y+1
       Zã             :  Subsections of Z of that length
             @        :  Map each array X
               Xx     :    Reduce by addition
              ¶       :    Check for equality with U
            x         :  Reduce by addition
     x                :Reduce by addition
```
[Answer]
# Java 10, ~~195~~ ~~194~~ ~~184~~ 182 bytes
```
n->{var L=new java.util.Stack();int i=1,k,x,s,r=0;for(;i++<n;){for(k=1;i%++k>0;);if(k==i)L.add(i);}for(x=L.size(),i=0;i<x;)for(k=i++,s=0;k<x;r+=s==n?1:0)s+=(int)L.get(k++);return r;}
```
-1 byte thanks to *@ceilingcat*.
-10 bytes thanks to *@SaraJ*.
[Try it online.](https://tio.run/##ZVJNbwIhFLz7KyhJEwh0s@hqGyn11pPtxWPbA2XR4G7RAGttjb/dwmpT114IM7w3zPtYyo28WZbVQdXSe/Akjd31ADA2aDeXSoPnBFsCKJROi3lk9r14@CCDUeAZWCDAwd487DbSgamw@hMso3DWBFNnsyBVhTBPyUYwWtEt9dSJnM9XDnFDyL3leJdAJRg314RUDzmPCfNICIOnmSxLZDDfp5itmGbefGuEqYka5n7L8TE3KlEfqSpSjggvhJ2wcY49Ecl51FnogCpCMHc6NM4Cx/cHnipZN@91rORU0GZlSvARW4FmwRm7eHkDEh/7ELQPqE9Z24QTHHRhQfNzOKT9czjqvt52c@@6kOUXP426YgWjgw6@cFZcWrvwNmCMDjsfsiGjRSekKPqMjv4Nve1RG9HOlbYbordrrYIu8d/SSBUaWcf9sJlKM2wfZl8@6I9s1YRsHRscaosMgePXAMkxnkAAECToiIT4FZ7AWaOU1qUur@AYPkpTpxsmEMOTxf3hBw)
**Explanation:**
```
n->{                // Method with integer as both parameter and return-type
  var L=new java.util.Stack();
                    //  List of primes, starting empty
  int i=1,k,x,s,    //  Temp integers
      r=0;          //  Result-counter, starting at 0
  for(;i++<n;){     //  Loop `i` in the range [2, `n`]
    for(k=1;        //   Set `k` to 1
        i%++k>0;);  //   Inner loop which increases `k` by 1 before every iteration,
                    //   and continues as long as `i` is not divisible by `k`
    if(k==i)        //   If `k` is now still the same as `i`; a.k.a. if `i` is a prime:
      L.add(i);}    //    Add the prime to the List
  for(x=L.size(),   //  Get the amount of primes in the List
      i=0;i<x;)     //  Loop `i` in the range [0, amount_of_primes)
    for(s=0,        //   (Re)set the sum to 0
        k=i++;k<x;  //   Inner loop `k` in the range [`i`, amount_of_primes)
        r+=s==n?    //     After every iteration, if the sum is equal to the input:
            1       //      Increase the result-counter by 1
           :        //     Else:
            0)      //      Leave the result-counter the same by adding 0
      s+=(int)L.get(k++);
                    //    Add the next prime (at index `k`) to the sum
  return r;}        //  And finally return the result-counter
```
---
It's basically similar as the [Jelly](https://codegolf.stackexchange.com/a/170939/52210) or [05AB1E](https://codegolf.stackexchange.com/a/170943/52210) answers, just 190 bytes more.. XD
Here a comparison for each of the parts, added just for fun (and to see why Java is so verbose, and these golfing languages are so powerful):
1. Take the input: (Jelly: 0 bytes) *implicitly*; (05AB1E: 0 bytes) *implicitly*; (Java 10: 5 bytes) `n->{}`
2. Create a list of primes in the range `[2, n]`: (Jelly: 2 bytes) `ÆR`; (05AB1E: 2 bytes) `ÅP`; (Java 10: 95 bytes) `var L=new java.util.Stack();int i=1,k,x,s,r=0;for(;i++<n;){for(k=1;i%++k>0;);if(k==i)L.add(i);}`
3. Get all continuous sub-lists: (Jelly: 1 byte) `Ẇ`; (05AB1E: 1 byte) `Œ`; (Java 10: 55 bytes) `for(x=L.size(),i=0;i<x;)for(k=i++;k<x;)` and `(int)L.get(k++);`
4. Sum each sub-list: (Jelly: 1 byte) `§`; (05AB1E: 1 byte) `O`; (Java 10: 9 bytes) `,s` and `,s=0` and `s+=`
5. Count those equal to the input: (Jelly: 1 byte) `ċ`; (05AB1E: 2 bytes) `QO`; (Java 10: 15 bytes) `,r=0` and `r+=s==n?1:0`
6. Output the result: (Jelly: 0 bytes) *implicitly*; (05AB1E: 0 bytes) *implicitly*; (Java 10: 9 bytes) `return r;`
[Answer]
# [Physica](https://github.com/Mr-Xcoder/Physica), 41 bytes
```
->x:Count[Sum@Sublists[PrimeQ$$[…x]];x]
```
[Try it online!](https://tio.run/##K8ioLM5MTvzvZhvzX9euwso5vzSvJDq4NNchuDQpJ7O4pDg6oCgzNzVQRSX6UcOyithY64rY/0AhoCq3aBPD2Nj/AA "Physica – Try It Online")
### How it works
```
->x:Count[Sum@Sublists[PrimeQ$$[…x]];x] // Full program.
->x:            // Define an anonymous function with parameter x.
    […x]        // Range [0 ... x] (inclusive).
        $$      // Filter-keep those that...
  PrimeQ        // Are prime.
 Sublists[...]  // Get all their sublists.
Sum@            // Then sum each sublist.
Count[...;x]    // Count the number of times x occurs in the result.
```
[Answer]
# [Haskell](https://www.haskell.org/), 89 bytes
```
g n=sum[1|a<-[0..n],_<-filter(n==).scanl1(+)$drop a[p|p<-[2..n],all((>0).mod p)[2..p-1]]]
```
[Try it online!](https://tio.run/##HcoxDgIhEEDRq0xhAdEli4kd2HgMQsxEEIkwEMBu746rxW9@3gv726c0ZwDS/ZON3FAtZhWC7OmulmdMwzdGWnPRH0hJsiM/uFYqoKlb3e35bzElxq4rF7k4qPx36yKttTNjJNBQW6QBAsJe8@hAKwXBj1uh4Wn0efkC "Haskell – Try It Online")
### Alternative, 89 bytes
```
f n=length$do a<-[0..n];filter(n==).scanl1(+)$drop a[p|p<-[2..n],all((>0).mod p)[2..p-1]]
```
[Try it online!](https://tio.run/##FcqxDoMgEIDhV7nBAdJKtEmngksfwzBcCijpeRBg7LtTHf7lz7dj/Xqi3gOwIc9b2weXAPW4TkqxfYVIzRfBxkhVP8g0i5scXEkZcM2/fMLHBe9IJMQySXUkB1leN4@ztf3AyGAgl8gNFISz4tGB0Ro2396Jm@dW@/MP "Haskell – Try It Online")
]


[Question]
      [
I was trying to find the shortest code possible that given a number n, returns the next prime palindrome number (limited to below 100000). If the number itself is a prime palindrome, the code should return the next one.
Write the shortest program/function that, when given an input `n` (less than `100000`), returns the next palindromic prime number.
This is an example working program:
```
def golf(n):
    n+=1
    while str(n)!=str(n)[::-1] or not all(n%i for i in xrange(2,n)):n+=1
    return n
```

[Answer]
# CJam, 15 bytes
```
li{)__mfsW%i^}g
```
Reads a single, positive integer from STDIN. [Try it online.](http://cjam.aditsu.net/)
### Example run
```
$ cjam <(echo 'li{)__mfsW%i^}g') <<< 250
313
```
### How it works
This uses a tricky prime check instead of the built-in `mp`:
`15 mf`, for example, pushes `[3 5]`. We cast to a string (`"35"`), reverse that string (`"53"`), cast to integer (`53`) and XOR the result with the original integer (`22`). Since the result in non-zero, `35` is not a palindromic prime.
```
li                 " N := int(input())        ";
  {          }g    " While R:                 ";
   )               "   N += 1                 ";
     _mfs          "   R := str(factorize(N)) ";
         W%i       "   R := int(reverse(K))   ";
    _       ^      "   R ^= N                 ";
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
```
<.ṗ↔
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/30bv4c7pj9qm/P9vaGz4PwoA "Brachylog – Try It Online")
Simple and neat.
```
?<.ṗ↔.     (Initial ? and final . are implicit)
?<.        Input is less than the output
  .ṗ       Output is a prime number
    ↔.     And output reversed is the output itself (it is a palindrome)
```
[Answer]
## CJam, ~~18~~ 17 characters
```
ri{)__s_W%=*mp!}g
```
How it works:
```
ri                     "Convert the input into an integer";
  {            }g      "Run this code block while the top stack element is truthy";
   )__                 "Increment the number and make two copies";
      s_               "Convert one of them to string and take another copy";
        W%=            "Reverse the last string and compare with second last";
           *           "If they do not match, make the second last number 0";
            mp!        "Put 1 to stack if number is not prime, continuing the loop";
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
## Python, ~~63~~ 60 characters
```
def g(n):
 n+=1
 while`n`[::-1]!=`n`or~-2**n%n>2:n+=1
 return n
```
[Answer]
### Mathematica - 75 characters
```
i=IntegerDigits;f@n_:=Select[Range[n+1,10^5],i@#==Reverse@i@#&&PrimeQ@#&,1]
```
Ungolfed:
```
i=IntegerDigits;
f@n_:=Select[
  Range[n+1,10^5],
  i@#==Reverse@i@#
  &&
  PrimeQ@#
  &,
  1
]
```
Sets an alias for the IntegerDigits function, then defines a function which selects the first number on the list of n+1 to 100,000 which satisfies PrimeQ and has palindromic digits. The function is called `f@50000`, returning `{70207}`.
[Answer]
## Haskell - 71
```
p n|s==reverse s&&all((/=0).mod m)[2..n]=m|1<2=p m where m=n+1;s=show m
```
Ungolfed
```
nextPrime n
  | s == reverse s && all ((/=0).(mod m)) [2..n] = m
  | otherwise = nextPrime (n + 1)
  where
    m = n + 1
    s = show m
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17
```
~Q1Wn`Q_`ePQ~Q1)Q
```
Explanation:
```
                         Implicit: Q = eval(input())
~Q1                      Q +=1
W                        while
 n                       not equal
  `Q                     repr(Q)
    `ePQ                 repr(end(prime_factorization(Q)))
 ~Q1                     Q += 1
)                        end while
Q                        print(Q)
```
[Answer]
# Ruby, 63
```
require"prime"
x=->n{Prime.find{|p|q=p.to_s;p>n&&q.reverse==q}}
```
## Explanation
* Input is taken as the arguments to a lambda. It's expected to be an `Integer`.
* `Prime` is `Enumerable`. Use `Enumerable#find` to find the first prime that's bigger than the input and is equal to itself when reversed.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 27 bytes
```
{~(x=.|$x)&/(2_!x)!'x}(1+)/
```
[Try it online!](https://tio.run/##y9bNz/7/P82quk6jwlavRqVCU01fwyhesUJTUb2iVsNQW1P/f3WFjaGBgUFtWoyh4X8A "K (oK) – Try It Online") for all test cases where the input `n<1000`
My first answer in K. Yay!
Thanks to @ngn for the help.
ngn also found a shorter solution which is very wasteful. Times out on TIO for `n>919`.
```
{x+(~x=.|$x)|/x=*/!2#x}/
```
### How?
```
{~(x=.|$x)&/(2_!x)!'x}(1+)/    # Main function f, argument x
 ~                             # Not
  (x=.|$x)                     # x equals the inverse of x (is a palindrome)
          &/                   # And reduction; will return truthy iff all
                               # results in the list are truthy (not 0)
            (2_!x)             # range [2..x]
                  !'x          # each modulo x
{                    }(1+)/    # While loop with x+1; returns x implicitly.
```
[Answer]
# Japt, 11 bytes
```
_¥sÔ©Zj}aUÄ
```
[Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=X6Vz1Klaan1hVcQ=&input=MTMx)
[Answer]
# JavaScript (E6) 95
```
Q=n=>(f=>{for(;a=!f;)for(f=++n==[...n+''].reverse().join('');b=n/++a|0,f&&a<=b;)f=a*b-n;})(0)|n
```
**Ungolfed**
```
Q=n=>
{
  for (f=0; !f;) // loop until both palindrome and prime
  {
    f = ++n == [...n+''].reverse().join(''); // palindrome check
    if (f) // if palindrome, check if prime
      for(a = 1; b=n/++a|0, f && a<=b; )
        f = a*b-n;
  }
  return n
}
```
**Test** In FireBFox/FireBug console
```
for (o=[],i=9;i<100000;)o.push(i=Q(i));console.log(o)
```
*Output*
```
[11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 10301, 10501, 10601, 11311, 11411, 12421, 12721, 12821, 13331, 13831, 13931, 14341, 14741, 15451, 15551, 16061, 16361, 16561, 16661, 17471, 17971, 18181, 18481, 19391, 19891, 19991, 30103, 30203, 30403, 30703, 30803, 31013, 31513, 32323, 32423, 33533, 34543, 34843, 35053, 35153, 35353, 35753, 36263, 36563, 37273, 37573, 38083, 38183, 38783, 39293, 70207, 70507, 70607, 71317, 71917, 72227, 72727, 73037, 73237, 73637, 74047, 74747, 75557, 76367, 76667, 77377, 77477, 77977, 78487, 78787, 78887, 79397, 79697, 79997, 90709, 91019, 93139, 93239, 93739, 94049, 94349, 94649, 94849, 94949, 95959, 96269, 96469, 96769, 97379, 97579, 97879, 98389, 98689, 1003001]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) (legacy), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[>ÐÂQsp*#
```
[Try it online](https://tio.run/##MzBNTDJM/f8/2u7whMNNgcUFWsr//xuaAgA) or [verify some test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3l/2i7wxMONwUWF2gp/6/V@W9oymVoYMBlaAzChiC2AQA).
**Explanation:**
```
             # (Implicit input)
             #  i.e. 15
             #  i.e. 130
[            # Start an infinite loop
 >           #  Increase the top of the stack by 1
             #   i.e. 15 + 1 → 16
             #   i.e. 100 + 1 → 101
  Ð          #  Triplicate that value
   Â         #  Bifurcate it (short for Duplicate & Reverse)
             #   i.e. 16 → 16 and '61'
             #   i.e. 101 → 101 and '101'
    Q        #  Check if it's equal (this checks if the number is a palindrome)
             #   i.e. 16 and '61' → 0 (falsey)
             #   i.e. 101 and '101' → 1 (truthy)
     s       #  Swap so the value is at the top of the stack again
      p      #  Check if it's a prime
             #   i.e. 16 → 0 (falsey)
             #   i.e. 101 → 1 (truthy)
       *     #  If it's both a palindrome and a prime:
             #    i.e. 0 and 0 → 0 (falsey)
             #    i.e. 1 and 1 → 1 (truthy)
        #    #   Stop the infinite loop
             # (Implicitly outputs the resulting value)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
[ÅNDÂQ#
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/@nCrn8vhpkDl//8NTQE "05AB1E – Try It Online")
```
[ÅNDÂQ#  # full program
      #  # exit...
[        # infinite loop...
      #  # when...
 ÅN      # first prime greater than...
         # implicit input...
   D     # or top of stack if not first iteration...
    ÂQ   # is equal to...
 ÅN      # first prime greater than...
         # implicit input...
   D     # or top of stack if not first iteration...
    Â    # reversed
         # (implicit) exit infinite loop
   D     # implicit output
```
[Answer]
# [Raku](http://raku.org/), 37 bytes
```
{first &is-prime&{.flip eq$_},$_^..*}
```
[Try it online!](https://tio.run/##Dcm9CoAgFAbQV/kIcYgS@6Epe5SkwQuCkmlLiM9uDmc6wUS3Vf@BE1TNZGN6wW0aQ7Te8CzI2QDzMF0Gpk8h@lLT9aFjGupAJrTpQHfEPmOSEnOzNKuUR/0B "Perl 6 – Try It Online")
The outer expression is `first EXPR, $_ ^.. *`, which looks for the first number which matches `EXPR` in the numbers from one greater than the input argument `$_` to infinity. (The caret `^` in front of the `..` means to exclude the starting point from the range.)
`EXPR` is an and-junction of two function, the built-in `&is-prime` and the anonymous function `{ .flip eq $_ }`, which tests for palidrome-ness. A number matches this junction only if it matches both members.
]


[Question]
      [
# Introduction
In number theory, a number is considered evil if there are an even number of 1's in its binary representation. In today's challenge, you will be identifying whether or not a given number is evil.
# Challenge
Your job is to write a full program or function which accepts a single, non-negative integer as input and outputs (or returns) whether or not that number is evil.
* You may output any [truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey#2194) value if the number is evil, and any falsy value if the number is not evil.
* You may input and output in [any acceptable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
* [OEIS sequence A001969](https://oeis.org/A001969) is the sequence containing all evil numbers.
* [Here](https://oeis.org/A001969/b001969.txt) is a list of the first 10000 evil numbers, for reference (and more test cases!)
* This question is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shorter, the better.
* Don't be put off by extremely short answers in golfing languages. I encourage you to submit in any language you like.
* Here are some test cases:
```
3 => True
11 => False
777 => True
43 => True
55 => False
666 => False
```
## The Leaderboard
At the bottom of the page is a stack snippet containing a leaderboard for this question. (Thanks, @MartinEnder)
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
/* Configuration */
var QUESTION_ID = 169724; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 81420; // This should be the user ID of the challenge author.
/* App */
var answers = [],
  answers_hash, answer_ids, answer_page = 1,
  more_answers = true,
  comment_page;
function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}
function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
  return a.owner.display_name;
}
function process() {
  var valid = [];
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if (OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    //else console.log(body);
  });
  valid.sort(function(a, b) {
    var aB = a.size,
      bB = b.size;
    return aB - bB
  });
  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function(a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
      .replace("{{NAME}}", a.user)
      .replace("{{LANGUAGE}}", a.language)
      .replace("{{SIZE}}", a.size)
      .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);
    var lang = a.language;
    lang = jQuery('<a>' + lang + '</a>').text();
    languages[lang] = languages[lang] || {
      lang: a.language,
      lang_raw: lang,
      user: a.user,
      size: a.size,
      link: a.link
    };
  });
  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);
  langs.sort(function(a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });
  for (var i = 0; i < langs.length; ++i) {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
      .replace("{{NAME}}", lang.user)
      .replace("{{SIZE}}", lang.size)
      .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }
}
```
```
body {
  text-align: left !important;
  display: block !important;
}
#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}
#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}
table thead {
  font-weight: bold;
}
table td {
  padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr>
        <td>Language</td>
        <td>User</td>
        <td>Score</td>
      </tr>
    </thead>
    <tbody id="languages">
    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr>
        <td></td>
        <td>Author</td>
        <td>Language</td>
        <td>Size</td>
      </tr>
    </thead>
    <tbody id="answers">
    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr>
      <td>{{PLACE}}</td>
      <td>{{NAME}}</td>
      <td>{{LANGUAGE}}</td>
      <td>{{SIZE}}</td>
      <td><a href="{{LINK}}">Link</a></td>
    </tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr>
      <td>{{LANGUAGE}}</td>
      <td>{{NAME}}</td>
      <td>{{SIZE}}</td>
      <td><a href="{{LINK}}">Link</a></td>
    </tr>
  </tbody>
</table>
```
*EDIT: I believe this question is not a duplicate of [this](https://codegolf.stackexchange.com/questions/47870/count-the-number-of-ones-in-an-unsigned-16-bit-integer), because whereas that question is asking to count the number of ones, this question is asking whether the number of ones is even. Although you **can** accomplish this question by simply counting the bits, there are [other approaches too](https://codegolf.stackexchange.com/a/169729/81420).*

[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 34 bytes
```
bool f(int i)=>i<1||i%2<1==f(i/2);
```
[Try it online!](https://tio.run/##ZY5BS8NAEIXP2V8xBIVdqJWkLQHT9NKToCh48GA9rOtGB@KsdCaCpPntcW1aETpzeMN7Mx/j@MKFrR9aRnqDh28W/1Eq11hmuIdOsVhBB18BX@HWImkD3fASQgO1RhJAU61wme12eJ4vs6qK7mVuykEl6ppklj89g3iWtWXPUEUgxJpN9pJloxZFMQ7zQ7BYTFRfqiRRdfzNuncNe9gfCpD@Yc0Buw7EofHTxy2K13CWxqvPVq6gO@72G7prZfRqfXRNn4IpTxE3SF6nG0pj2P/28AM "C# (.NET Core) – Try It Online")
There were already a few C# solutions, but this is the first recursive one.
In the case case when no more `1`'s are present, the function is terminated with a positive result. Otherwise the lowest bit is tested. If it is set, then the count of the rest of the bits must be odd. If it is unset, then the count of the rest of the bits must be even. We are able to determine whether the count of the remaining bits is even/odd by making a recursive call to half the input.
[Answer]
# [SML](http://sml-family.org), 32 Bytes
```
fun%0=1| %n=(n+ %(n div 2))mod 2
```
**Explaination:**
* `%` is function name
* takes in input in repl and returns 1 if evil, 0 otherwise
* `n` is input, returns (n + %(n//2)) % 2
Made by 2 bored Carnegie Mellon Students
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 20 bytes
-6 bytes thanks to Roberto Graham
```
n->n.bitCount(n)%2<1
```
[Try it online!](https://tio.run/##jZA9C8JADIb3/oogCHeoB/WDDn4sguDg5CgO11ol9UyLlxOk9LfXaxUUujglPHnz5iPTDz3KTtc6Mdpa2GmkMgAoXGwwAcuafXjkeIKbL4k935EuhyPo@8VKKAOvBci8iXKMRp0dJYw5qS3x5pODh7CsabQiFSOvc0csSPbHi7BuuudvE04ti8mwUcv5l4RhB0VR1GHTbuds9kVVM@P3mlaBxIDDP9aXZWu7f1pObyp3rAr/BzYkcNCD5Qp6A69SuijMU6D8jKzqFw "Java (JDK 10) – Try It Online")
[Answer]
# Rust, 24 bytes
```
|x:u8|x.count_ones()&1<1
```
Note that this only works for 8-bit numbers.
The following works for 64-bit (but is an extra character):
```
|x:u64|x.count_ones()&1<1
```
Testing code:
```
fn main() {
    let f = |x:u64|x.count_ones()&1<1;
    const TESTS: [(u64, bool); 6] = [
        (3, true),
        (11, false),
        (777, true),
        (43, true),
        (55, false),
        (666, false)
    ];
    for (x, b) in TESTS {
        assert_eq!(f(x), b);
    }
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
b1O₂
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJiMU/igoIiLCIiLCI3NzciXQ==)
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 53 bytes
```
: f 1 swap begin 2 /mod -rot xor swap ?dup 0= until ;
```
[Try it online!](https://tio.run/##JYxBCsIwFET3PcWj@0RjLQGLeha1pha0@XxT9PYxwc0bZoaZEDU9zBSq5Hwg4Hh/LsL1Ps0LOzavOGI0Jr5R/9V5XIXtkXVJ85OhrIQadVjFtmBOtOXJclOGpkMa5wq894X76vseyT8 "Forth (gforth) – Try It Online")
### Explanation
Takes the xor-sum of the digits of the binary form of the number. (repeatedly divides by 2 and xors the remainder with the "sum" value)
### Code Explanation
```
: f              \ begin a new word definition
  1 swap         \ place 1 on the stack below the input (n)
  begin          \ start an indefinite loop
    2 /mod       \ get the quotient and remainder of dividing n by 2
    -rot         \ move the sum and remainder to the top of the stack
    xor          \ xor the sum and remainder
    swap         \ move the quotient back to the top of the stack
    ?dup         \ duplicate if > 0
    0=           \ get "boolean" indicating if quotient is 0
  until          \ end the loop if it is, otherwise go back to the beginning
;                \ end the word definition
```
[Answer]
# Java 8, ~~40~~ 36 bytes
```
n->n.toString(n,2).chars().sum()%2<1
```
-4 bytes thanks to *@Okx* for something I shouldn't have forgotten myself..
[Try it online.](https://tio.run/##ZY9LC8IwEITv/opFEBK0gfqg4OvuQS8e1cMao0bbjTRbQcTfXtPag@JlYZid/WYveMfocriWOkXvYYmWni0AS2zyI2oDq0oC7J1LDRJosQjWyeRAchKcVysMz8hWwwoIZlBSNCfFbs25pZOgXl8qfcbcC6l8kQnZ6U/jclLlbsU@Dbkmfnf2AFkoID7RzQ5QfuhsPItBDWxEHH@rJEm@5fBndTT6a1qjajM8CrahrB@eTaZcweoWCnBKwnbb4y23u6S0sLK58yrf)
**Explanation:**
```
n->                // Method with Integer parameter and boolean return-type
  n.toString(n,2)  //  Convert the integer to a binary String
   .chars()        //  Convert that to an IntStream of character-encodings
   .sum()          //  Sum everything together
    %2<1           //  And check if it's even
```
Note that the character encoding for `0` and `1` are `48` and `49`, but summing them and taking modulo-2 still holds the correct results because `48%2 = 0` and `49%2 = 1`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
.+
$*
+`(1+)\1
$+0
0
11
^$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSztBw1BbM8aQS0XbgMuAi8vQkIsrTuX/f2MQy9zcnMvEmMvUFAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
+`(1+)\1
$+0
```
Partial binary conversion (leaves extra zeroes).
```
0
```
Delete all the zeros.
```
11
```
Modulo the ones by two.
```
^$
```
Test whether the result is zero.
[Answer]
# x86 Assembly, ~~12~~ 11 bytes
```
F3 0F B8 44 24 04  popcnt      eax,dword ptr [esp+4] ; Load EAX with the number of ones in arg
F7 D0              not         eax ; One's complement negation of EAX
24 01              and         al,1 ; Isolate bottom bit of EAX
C3                 ret
```
-1 byte thanks to @ceilingcat's suggestion
[Answer]
# Pyth, 6
```
!xFjQ2
```
### Explanation
```
   jQ2 # Convert input to base 2 list
 xF    # reduce on XOR
!      # logical negation
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 33
```
dc -e2o?p|tr -d 0|wc -c|dc -e?2%p
```
[Try it online!](https://tio.run/##RcqxCsIwFEDRvV9xKXYs2NaSQbQ/4lKTV9olLyQBl/x7FEEc7@E@17TXTSNZUrZrEg7PxDBgjOEyMc9XnDYhHj5vtF3idqfl9Psbsbv@k8KjOksvoy6h5EjvOJfXR2z5@jJ2oTr1Ut8 "Bash – Try It Online")
Reads input from STDIN. Outputs 1 for True and 0 for False.
* `dc` converts input to a binary string
* `tr` removes zeros
* `wc` counts remaining ones (and trailing newline, which corrects sense of logic
* `dc` calculates count mod 2 and outputs the answer
[Answer]
# Python 2, ~~28~~ 27 bytes
```
f=lambda n:n<1or n&1^f(n/2)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qz8Ywv0ghT80wLk0jT99I838aiKuQmadgrKNgaKijYG5urqNgAuSYmlpxcRYUZeaVaACVamr@BwA "Python 2 – Try It Online")
Returns a truthy value if exactly one of `the ones-bit is a 1` and `the result of calling this function on n/2 is truthy` is true (or `n==0`). It works because `n/2` is equivalent to a right bitshift with floor division (so Python 2 only).
## Alternate version, also ~~28~~ 27 bytes
```
g=lambda n:n<1or g(n&n-1)^1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P902JzE3KSVRIc8qz8Ywv0ghXSNPLU/XUDPO8H8akJunkJmnYKyjYGioo2Bubq6jYALkmJpacXEWFGXmlWgAlWtq/gcA "Python 2 – Try It Online")
Based on the K&R method of counting set bits referenced by vazt.
Both of these could be two bytes shorter if the output allowed falsey to mean evil.
**Edit:** Thanks to Amphibological for saving a byte!
[Answer]
# [J](http://jsoftware.com/), 9 bytes
Anonymous tacit function. Can take any integer array as argument.
```
1-2|1#.#:
```
[Try it online!](https://tio.run/##y/r/P83WylZfrcZKTdnqf2pyRr5CmoKxgqGhgrm5uYKJsYKp6X8A "J – Try It Online")
`1-` one minus (i.e. logical negation of)
`2|` the mod-2 of
`1#.` the sum (lit. the base-1 evaluation) of
`#:` the binary representation
[Answer]
# C#, 65 bytes
So I'm terrible at codegolf, but here's my hacky string + LINQ solution:
```
n=>{return Convert.ToString(n,2).Where(c=>c=='1').Count()%2==0;};
```
[Try it online!](https://tio.run/##TY6xagMxEERr6yu2CZbAEY5TKrrGJFUMBgdchBSKLC4L512yqzsw5r79cjiNpxuY95isj5mlTL0itXC4aC3nYO6bf0f6DcbkLqnCXriVdIarWWhNFTMMjCfYJSSrVWbs8wuStOrmCdzlraf8glRX8M3cNYD6OmAHESaKzVVK7YVgyzQUqf6DDzeXpdXG@eNPkWJzbHKMy6el81vuqVr3sIlxHcYwLWZOuSv@KFjL/LfYf719di7cboxmnP4A "C# (.NET Core) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~50~~ ~~48~~ 45 bytes
-3 bytes thanks to Charlie
```
n=>{int i=0;for(;n>0;n/=2)i^=n%2;return i<1;}
```
[Try it online!](https://tio.run/##lY5BS8NAEIXv@RVzERLQpmktMWw3l0JPCoKCB6mwbjdlYJ2FmU2hlPz2mNYK4il9x8f7eJ@VOxvY9dYbEXhOjgkMkWgiWmBntoH8AV4OEt3XZN2SXSLFW/gMwdfQgO5J18ehAtRT1QROFdVTRbmeZfih6Wam2MWWCXBZqK6HS1Ty92cfcAtPBimVyEi79w0Y3kl23vwYnXKxWAWS4N3kjTG6RySXNuk8y9SwyHN45daNIYrijAzE2ngZhZRleWKuOLmf/56MJRaLq7WKqqoe/ot1Sdd/Aw "C# (.NET Core) – Try It Online")
[Answer]
# Excel, ~~43~~ ~~41~~ ~~39~~ 41 bytes
*-2 bytes thanks to Keeta
-2 bytes thanks to Sophia Lechner
+2 bytes thanks to sundar*
Original:
```
=MOD(LEN(SUBSTITUTE(DEC2BIN(A1),0,"")),2)=0
```
Shortest version:
```
=MOD(LEN(SUBSTITUTE(DEC2BIN(A1),0,)),2)=0
```
[Answer]
# C (gcc), 29 bytes
`f(a){a=!__builtin_parity(a);}`
Uses a GCC builtin, and exploits how GCC handles return values, only works at `-O0` optimization level (the default).
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYFNckpKZr5dh9z9NI1GzOtFWMT4@qTQzpyQzL74gsSizpBIobF37PzcxM09Ds5pLQaGgKDOvJE1DSUHBWEHXTkE1JSZPSUchTcNYU9MaWdrQEEXa0BBV3tzcHEUeyEczwATVfBN0C0xNUeRNTUHytf8B "C (gcc) – Try It Online")
[Answer]
# [JavaScript (Babel Node)](https://babeljs.io/), 39 bytes
*-1 Bytes thnks to @OMᗺ =D*
```
_=>eval('for(z=0;_;_>>=1)z+=_&1;z%2<1')
```
[Try it online!](https://tio.run/##ZcjBCoQgEADQe/9ROSyFUwse3PFXxEpjF2milg7@vJ3Dd3w/d7lzPr77v5vc5GO38eJzoGzJ@MtF0QY@RCKprbbGEEJ6kW1Qp3r4YAt55u3k6PvIqwhCAlTPQSxKKVXcewTINw "JavaScript (Babel Node) – Try It Online")
[Answer]
## MATLAB / Octave, 28 27 25 bytes
Using the `de2bi` function from the comm. systems MATLAB toolbox, you can achieve 25 bytes
```
@(n)~mod(sum(de2bi(n)),2)
```
Here is the 27 byte version which works without toolboxes (so works in Octave):
```
@(n)~mod(sum(dec2bin(n)),2)
```
The `dec2bin` conversion outputs a character array, so counting the occurence of the character `'1'` mod 2 gives the opposite of an evil number, negating that with `~` gives the answer.
Edited to include Sundar's comments (made it a valid anonymous function and saved by leveraging ASCII values instead of comparing to `'1'`).
[Answer]
# Lua 5.3.4, ~~63~~ 62 bytes
*-1 bytes thanks to Jo King*
```
function e(n)o=0while n>0 do o=o+n n=n//2 end return o%2<1 end
```
More readable version:
```
function e(n)
  o=0
  while n>0 do
    o=o+n
    n=n//2
  end
  return o%2<1
end
```
`n` is the input and integer divided by 2 until it is equal to 0. `o` is incremented by `n`, and its parity is what determines the output. This function returns true if evil or false if odious (not evil).
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~16~~ ~~14~~ ~~11~~ 10 bytes
Can't believe there's no CJam/GolfScript answer yet.
```
qi2b1e=1&!
```
[Try it out! (Online)](http://cjam.aditsu.net/#code=qi2b1e%3D2%250%3D&input=503)
---
**Explanation**
```
qi                     Reads input as an integer
  2b                   Converts it to an array of its digits in base 2 (binary)
    1e=                Checks the number of occurrences of 1 in that array
       1&              The rightmost bit of the number of 1s (a test for evenness)
         !             Unfortunately we need to return 1 for evenness and not 0 (and vice versa)
                       Implicit output 1 for true and 0 for false
```
---
This answer isn't very good in comparison to other answers here, but I might as well post and see if some CJam people can help golf this answer further.
---
### Changes:
[Helen](https://codegolf.stackexchange.com/users/58707/helen) cut off 2 bytes!
Old: `qi2b1e=2%0={1}0?`
New: `qi2b1e=2%0=X0?`
By replacing the block (`{1}`) with `X` (whose value is always initialised to 1) we can cut out 2 characters and don't have to add in any whitespace.
The If-Else still works without the block, funnily enough.
---
[Helen](https://codegolf.stackexchange.com/users/58707/helen) cut off 3 bytes!
Old: `qi2b1e=2%0=X0?`
New: `qi2b1e=2%0=`
We don't need to manually push `1` and `0` to the stack depending on the result of the comparison since `1`/`0` are automatically pushed for `true`/`false` respectively.
---
[Helen](https://codegolf.stackexchange.com/users/58707/helen) cut off 1 byte!
Old: `qi2b1e=2%0=`
New: `qi2b1e=1&!`
By keeping the rightmost bit of the number, we can test for evenness without having to use modulo.
[Answer]
# [Alchemist](https://github.com/bforte/Alchemist), ~~117 105 99~~ 93 bytes
```
_->In_a+s
a+0z->z
a+z+0c->b
z+0a+0c+f->
z+0a+0c+0f->f
b+0a+0z->c
c+0b->a
0a+0b+0c+0z+s->Out_f
```
[Try it online!](https://tio.run/##PYoxDoAgDEX3XqVpggtjdyePQAAlmqiYgAuHt1YGp/ffy/d7XJdjK1XEEY@n81jAo2nETdnQROIASo0RE/G/jUqC0E3vETQFYg9fCP3RsBBPd3VJxFr75Ktu@SxC8/AC "Alchemist – Try It Online")
Trying out BMO's new language! Outputs `0` if the number is evil and `1` otherwise. It took me quite a while to figure out how to check if there is only one of an atom left.
### Explanation:
```
Input
_->In_a+s     Convert the initial _ atom to input copies of atom a
              And an s atom as a flag
Division
a+0z->z       Always have one z atom by converting an a atom
a+z+0c->b     Convert an a atom and a z atom to a b atom
              This divides the a atoms by 2 into b atoms
              With a z atom as the parity
z+0a+0c+0f->f Convert the z atom to an f atom if there aren't any f atoms
z+0a+0c+f->   If there is an f atom, remove both
Reset to calculate the next binary digit
b+0a+0z->c    Convert all b atoms to c atoms
c+0b->a       Convert all c atoms to a atoms
Output
0a+0b+0c+0z+s->Out_f  If there are no relevant atoms left
                      Output the number of f atoms
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
b1¢È
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yfDQosMd//@bmZkBAA "05AB1E – Try It Online")
Converts to binary `b`, counts occurrences of 1 `1¢`, and checks if it's even `È`.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 41 bytes
```
: f 1 swap 63 for 0 d2* m+ next + 2 mod ;
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WymkKRgqFJcnFiiYGSsABRUMFFKMtBRytRXyUitKFLQVjBRy81MUrP@rGhoaGgAhUIMelyqYCeH8BwA "Forth (gforth) – Try It Online")
A function with signature `( u -- 0-or-1 )`, that is, one that takes a cell-sized integer from the stack and gives a 0 (not evil) or 1 (evil) on the stack. gforth's native boolean is -1 (true) and 0 (false), but any nonzero value is recognized as true, just like many other languages.
Unlike [the answer to a very similar challenge](https://codegolf.stackexchange.com/a/194276/78410), the FP trick seems to fail to save bytes here.
### How it works
```
: f ( u -- 0-or-1 ) \ Declare function f
  1 swap 63 for     \ Store a 1 under u, and loop 64 times ( 1 u )
                    \ The 1 is bit-count + 1
    0               \   Push a 0 (i.e. cast to unsigned double-cell int)
    d2*             \   Shift double-cell int left once ( 1 u' 0-or-1 )
                    \   In effect, shift MSB of u into the top
    m+              \   Add double [1 u'] and single [0-or-1]
                    \   In effect, add the bit to the bit-count
  next              \ End loop ( bc+1 0 )
  + 2 mod           \ Remove the dummy 0 at the top, and take modulo 2
;
```
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [8 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
›1¢|▬║~Ô
```
# Explained
Unpacked: `!(+\(:_b%2`
```
! Boolean not
  ( Expression
    +\ Fold with addition
      ( Expression
        :_ Format implicit variable _ (initialized as stdin)...
          b ... to binary
        %2 Modulo 2
      ) Implicit, can be removed
  ) Implicit, can be removed
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes
```
¬F≠ḋ
```
[Try it online!](https://tio.run/##yygtzv7//9Aat0edCx7u6P7//7@ZmRkA "Husk – Try It Online")
-1 byte from Jo King.
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 47 bytes
```
(load library)
(d E(q((N)(even?(sum(to-base 2 N
```
[Try it online!](https://tio.run/##DcorEoAgAAXA7ilefASDohBNVO@AA4EZ/AE6w@nRzVvCUWPIV2uMp3WIYUs2VdHRwfAmV0H/@mNhfnaWs99s9hixto67vWDwJ4lhgNYak8Q8QyklRPsA "tinylisp – Try It Online")
Straightforward solution, thanks to useful `library` functions.
[Answer]
## Wolfram Language (Mathematica), 27 bytes
This is my first ever post on code golf, and I am doing this mostly to hone my Mathematica skills. Any suggestions are greatly appreciated!
```
2∣Tr[IntegerDigits[#,2]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73@hRx@KQomjPvJLU9NQil8z0zJLiaGUdo9hYtf8BRZl5JQ4hiUk5qdFp0ZmxOtWZOgY6hgYGtbH/AQ "Wolfram Language (Mathematica) – Try It Online")
This works by checking the parity of the base-2 digit sum (also called the digital sum). The method is slightly different than the other Mathematica answers.
Edit: I was able to save three bytes by changing Total -> Tr. This was found in the tips page suggested in the comments.
[Answer]
# Python 3.10, 25 bytes
```
lambda x:~x.bit_count()%2
```
It's the same number of char that [Lynn's answer](https://codegolf.stackexchange.com/a/169873/112099) but with a totally "new idea".
The `.bit_count()` is new in Python 3.10 and returns the number of 1.
So with that, you can make it 25 bytes.
Note: I can't put a "Try It Online" because their version of Python is 3.7.8
But thank's to [@pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)'s comment:
 [You can test the code here](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuha702xzEnOTUhIVKqzqKvSSMkvik_NL80o0NFWNICpuKqblFylkKmTmKRQl5qWnahgaGGhaFRRlAhVl6qRpZGpqQhTCjAQA)
[Answer]
# [Flobnar](https://github.com/Reconcyl/flobnar), 22 bytes
```
> +
|\<:
:&%!@
/<2
2 :
```
[Try it online!](https://tio.run/##S8vJT8pLLPr/305Bm6smxsaKy0pNVdGBS9/GiMtIwer/f0OD/7opAA "Flobnar – Try It Online")
```
<
%!@   Output 1 if the result of `<` is divisible by 2, 0 otherwise...
2
 \    Recursive call:
:&    set current value to input value, or
/<    the previous value divided by 2
2
   :
 > +
:| <  If the current value is 0, return current (0);
 :    otherwise add the current value to the result of recursive call
```
]


[Question]
      [
While moving, I broke my lamp. Now, I need a new one. It's your job to make me a lamp! I'm not sure what size I want, though I know I want a squiggly one.
Your program/function must take in a number input, and print out a lamp with that many squiggles/bumps.
**Examples:**
Input:`2`
Output:
```
/--\
 ()
 ()
/__\
```
Input:`3`
Output:
```
/--\
 ()
 ()
 ()
/__\
```
Input:`5`
Output:
```
/--\
 ()
 ()
 ()
 ()
 ()
/__\
```
**Rules:**
* 0 & negative numbers don't matter
* To give the lamps (an this challenge) more of a variety, you **must** change the lamp shade.
	+ They must be **4** characters wide and **1** character high.
	+ They can be in any shape, including non-lamp-shade shapes.
	+ They must not contain whitespace.
	+ The base must stay the same.
* You must show an example input & output with your lamp shade.
* Shortest code wins!

[Answer]
# Java ~~7~~ 11, ~~84~~ ~~83~~ 37 bytes
```
n->"i!!i\n"+" ()\n".repeat(n)+"/__\\"
```
[Try it online.](https://tio.run/##nVFBTsMwELz3FdNcsNUkpSBOFdxBohzg1lSVm2xJSmJH9qaoQn17cFpLFRJcuFhez8yOd3an9irZFR99Xivn8Kwq/TUCKs1ktyonLIYSeGVb6XfkwiPQcu4fjyN/OFZc5VhA4x69Th6iajyuMh1NLLWkWEQQ0pexlpNoul5nWdTPB2HbbWovDPq9qQo03lycjZYrKBmcD46pSU3HaeshrrXQaS5u5OkTv@J/I4Py9t/KO3kZfDrF2@MLCkNOXzFc17bGMp58npjNcCCO4QxKsoQQxXm02PeTaIhLU4ANqOlqxRQSTgP3RNoaCy4JTjWEzYEpyU2n@RJ72MqP/h6zgwdUM5BDipa4sxqaPoNIDNe8VHZ55q3kYF37lYsou45i3yUMe@y/AQ) (NOTE: Java 11 isn't supported on TIO yet, so `String.repeat(int)` has been emulated with `repeat(String,int)` for the same byte-count.)
Uses `i!!i` as cap. [`¡!!¡` looks better](https://tio.run/##nVFBbsIwELzziiGX2iKE0qon1N5bqfTQ3ghCJlma0MSO7A0VqngMX@Fj1AFLqFJ76cXyenZmvLNrtVHDdf5xzCrlHJ5Vqb96QKmZ7EplhGlXAq9sS/2OTHgEWk78467nD8eKywxTaNzjqIcP0WHf7x/2qY4GlhpSLCII6ctYy0E0WizSNDpOOmrTLitPDQobU@aovb04W83mUDJ4bx1TnZiWk8ZDXGmhk0zcyNM3fsX/Rjrm7b@Zd/Iy@miEt8cX5IacvmK4tmmMZTz5RDEeY0scwxkUZAkhivNosdeTqIkLk4MNqG4rxRQyTkLvqWllLLggOFUTllumYWZazZfgw15@6HvMdh5QddccUrTErdXQ9BlIortmhbKzc99cdtaVX7qI0uso9iph2N3xGw), but is two bytes more.
**Explanation:**
```
n->                    // Method with integer parameter and String return-type
  "i!!i\n"             //  Return the cap + new-line
  " ()\n".repeat(n)    //   appended with " ()" and a new-line `n` amount of times
  "/__\\"              //   append with "/__\"
```
[Answer]
## [Perl 5](https://www.perl.org/), 24 bytes
```
$_=$<.'
 ()'x$_.'
/--\
'
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbFRk@dS0FDU71CJR7I0tfVjeFS///fkMuIy5jLhMv0X35BSWZ@XvF/3QIA "Perl 5 – Try It Online")
Uses `1000` as the cap.
[Answer]
# [Ahead](https://github.com/ajc2/ahead), 38 bytes
```
I"|MM|"Wr
~W" ()"oN<s!:-1~
@W"/__\"oN<
```
[Try it online!](https://tio.run/##S8xITUz5/99TqcbXt0YpvIirLlxJQUNTKd/PpljRStewjsshXEk/Pj4GJPL/vzEA "Ahead – Try It Online")
## Samples
```
1
|MM|
 ()
/__\
2
|MM|
 ()
 ()
/__\
3
|MM|
 ()
 ()
 ()
/__\
```
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 50 bytes
```
"\__/"&v
0-1_v#:<g00" ()"*25p0
*25$<>:#,_@#::::"_"
```
[Try it online!](https://tio.run/##S0pNK81LT/3/XykmPl5fSa2My0DXML5M2com3cBASUFDU0nLyLTAgAtIqtjYWSnrxDsoWwGBUrzS//9GAA "Befunge-93 – Try It Online")
Example with Input 3
```
____
 ()
 ()
 ()
/__\
```
[Answer]
# PHP, 38 bytes
```
/--\<?while($argn--)echo"
 ()"?>
/__\
```
Save to file; run as pipe with `-nF` or [try it online](http://sandbox.onlinephpfunctions.com/code/c5e0381f8ab130c7da04b87d5f6577a1eb26e8c3).
[Answer]
# Noether, 26 bytes
```
"-"4*P?I(" ()"P?!i)"/__\"P
```
[**Try it online!**](https://beta-decay.github.io/noether?code=Ii0iNCpQP0koIiAoKSJQPyFpKSIvX19cIlA&input=Mw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal/wiki), ~~16~~ ~~12~~ 10 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page)
```
8Ｅ⊕Ｎ(←_/‖Ｍ
```
-4 bytes thanks to *@ASCII-only*.
-1 byte thanks to *@Neil* by using a `Map`.
[Try it online (verbose)](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJQknTmgvC9k0s0PDMSy5KzU3NK0lNAbILSkv8SnOTUos0NDV1FJQ0lDThiq18UtNKgGLx@iADglLTclKTS3wzi4rygYqt//83@a9blgMA) or [try it online (pure)](https://tio.run/##ASMA3P9jaGFyY29hbP//OO@8peKKle@8rijihpBfL@KAlu@8rf//NA).
Uses `8()8` as cap, but the `8` can be any character from Charcoal's code-page that isn't used as a command/operator.
**Explanation:**
Print `8`:
```
Print("8");
8
```
Print `(` the `input+1` amount of times downwards:
```
Print(Map(Incremented(InputNumber()), "("));
Ｅ⊕Ｎ(
```
Then after that print `_/` in a left direction:
```
Print(:Left, "_/");
←_/
```
And finally mirror everything vertically:
```
ReflectMirror();
‖Ｍ
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 164 bytes
```
({}<((((((((((()()){}()){})()){}()){}())){}()))[[]]()){({}<>)<>}<>>()){({}[()]<(((((((()()){}()){}){}){}())[()])[(()()()()){}])((()()()()()){})>)}(((({}{}{}{}{}))))
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O61kYDATQ1NDWra8EEEhNIQMno6NhYkBBIm52mjR2QtIPyozU0Y22wmQNGQCZIAZAAyUHlYzU14FyIWjvNWpD26loYBNqp@f@/6X9dRwA "Brain-Flak – Try It Online")
Output for `5`:
```
{{{{
 ()
 ()
 ()
 ()
 ()
/__\
```
]


[Question]
      [
I can't believe we don't have this already.. It's one of the most important data-structures in programming, yet still simple enough to implement it in a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"):
## Challenge
Your task is to implement a stack that allows pushing and popping numbers, to test your implementation and keep I/O simple we'll use the following setup:
* Input will be a list of non-negative integers
Every positive integer \$n\$ indicates a \$\texttt{push(}n\texttt{)}\$ and every \$0\$ indicates a \$\texttt{pop()}\$ - discarding the top element.
* Output will be the resulting stack
## Example
For example if we're given \$[12,3,0,101,11,1,0,0,14,0,28]\$:
$$
 \begin{aligned}
 & 12 & [12] \\
 & 3 & [3,12] \\
 & 0 & [12] \\
 & 101 & [101,12] \\
 & 11 & [11,101,12] \\
 & 1 & [1,11,101,12] \\
 & 0 & [11,101,12] \\
 & 0 & [101,12] \\
 & 14 & [14,101,12] \\
 & 0 & [101,12] \\
 & 28 & [28,101,12]
 \end{aligned}
$$
Output will be: \$[28,101,12]\$
## Rules
* Input will be a list of non-negative integers in any [default I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
	+ you may use a negative integer to signify the end of a stream of integers
* Output will be a list/matrix/.. of the resulting stack
	+ your choice where the top element will be (at the beginning or end), the output just has to be consistent
	+ output is flexible (eg. integers separated by new-lines would be fine), the only thing that matters is the order
	+ you may use a negative integer to signify the bottom of the stack
* You're guaranteed that there will never be a \$0\$ when the stack is empty
## Examples
```
[] -> []
[1] -> [1]
[1,0,2] -> [2]
[4,0,1,12] -> [12,1]
[8,3,1,2,3] -> [3,2,1,3,8]
[1,3,7,0,0,0] -> []
[13,0,13,10,1,0,1005,5,0,0,0] -> [13]
[12,3,0,101,11,1,0,0,14,0,28] -> [28,101,12]
```

[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
"@?@}x
```
Input is a row vector of numbers.
The final stack is shown upside down, with the most recent element below.
[Try it online!](https://tio.run/##y00syfn/X8nB3qG24v//aEMjHWMdAx1DA0MdQyACMoEcEyBhZBELAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8F/Jwd6htuJ/bKy6rq56hEvI/@hYrmhDENYx0DEC0iZA2lDHEMS00DEGMo10jMHSxjrmQCkgBPGMQaqAsiC1QGxgYKpjipAFagGLAs0xBCsAckDmGlnEAgA).
### Explanation
```
"         % For each element in the input (implicit)
  @       %   Push current element
  ?       %   If non-zero (this consumes the current element)
    @     %     Push current element again
  }       %   Else
    x     %     Delete most recent element
          %   End (implicit)
          % End (implicit)
          % Display (implicit)
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 42 bytes
Since "[the] output is flexible [...], the only thing that matters is the order", this changes the input array into a `0`-terminated array. Example : `[1,0,2]` will return `[2,0,2]` which is to be interpreted as `[2`~~`,0,2`~~`]` = `[2]`.
```
a->{int s=0;for(int v:a)a[v>0?s++:--s]=v;}
```
[Try it online!](https://tio.run/##bVBdb4IwFH33V9z4BKMQ0JkZEM2y52XJ9mh8qAiuCoW0hcwYfju7LfiRuZC095577unhHGhD3cPu2LGiKoWCA/ZerVjuPUWjByyreaJYyfWwqrc5SyDJqZTwThmH8whgQKWiCq@mZDsocGZ9KcH4fr0BKvbSNlSAt5LLukjFgnG13iwhg7ij7vKMLcjYj7JSWLpuQmrTdbP0V9JxQteVm7iJ2i4yImYXhVUqlYR4kAY4t@RSBXcl8cnk1s7JlARkQqb3jCl5QRZ@d@AUezwCPHXl@zMyeyChjhkGJAgMD5tn/eB8ILW9ZfwvsBoqjOewd25fjX@dpEoLr6yVV2FoynoVgp6kp8o@REvzbXBgHMLYjoatzKNJklaqn15QnR7ju/QHg3GDK3fIlSHqR3gtjAcvT/lefSPgODc7KJKBUV2zDcS4gbOrKItgK1J6jKAd@Jdbb2iCIS7Ah1UPhTD8T1JWp4/sk/J9auQJ@KSnX@3/jSLn/4cxLOin21Hb/QI "Java (JDK 10) – Try It Online")
# Previous versions:
## [Java (JDK 10)](http://jdk.java.net/), 60 bytes
```
l->{for(int i;(i=l.indexOf(0))>0;l.remove(i))l.remove(--i);}
```
[Try it online!](https://tio.run/##dVHRToMwFH3fV9z41GppYLi4jI3E@GSi8WGPyx4qK0tnKaQt02Xh27F0iJjFkJZz7jk99xYO7MiCw@6jFUVVagsHx2lthaS3yeSqltcqs6JUnVjV71JkkElmDLwyoeA8AeirxjLrXsdS7KBwGlpbLdR@swWm9wZ7K8BTqUxdcL18EcYun5Xle67TFPJVK4P0nJcaCWVBJEisJBVqx7/echRinIaJpJoX5ZEjgfGAg0DgpGkTn97nbbauq@XGGlj1fQHODflB0QiSkEx/6ZzEJCJTEo8dMXlwLveMirHjbovc3qEwnJHZlcnleDEiUeR9jtx3Dee9qbmM3d16GN0PvriMj4fp/3wukI65qyn@CY9as5NXU@Sxocx0HHUJGCd9wPpkLC9oWVtauf9ikc@4g5sF3AymnLIs49VF/PeoVGO9mXSrab8B "Java (JDK 10) – Try It Online")
**Credits:**
* -1 byte thanks to [O.O.Balance](https://codegolf.stackexchange.com/users/79343/o-o-balance)
## If I can end the program with errors: 55 bytes
(though everything is properly modified)
```
l->{for(int i;;l.remove(--i))l.remove(i=l.indexOf(0));}
```
[Try it online!](https://tio.run/##dVFdb4IwFH33V9z4BFshIDMzoiTLnpZs2YN7Mz5ULFpXCmkvOkP47ax8jLmYpWm5597Duee2R3qiznH3WfM0zxTC0WC3QC7cu3B0k0sKGSPPZFPMi63gMcSCag1vlEsoRwB9ViNF8zllfAepqVkrVFzu1xugaq/tlgrwnEldpEwtXrnGxYtEtmcqiiBZ1sKJyiRTFpcIPAyFq1ianZjlONy2B8SXwuVyx77eE8uz7bCqw1a4l1pvTENkGjUs@5YAZUV@Iv8qJB6Z/MIZCYhPJiS4ZgTk0bDMukoGBpvDN2cTed6UTG9IRqct@sT3W54BD03DWU@qOtvNwIP11vi8s28P7v/cFAiDzGiSneFJKXppq5HVxtqlusFWo2DuphdYXTSy1M0KdHPzJGi1GvcwnsN4IKG6QAmJS@OY5R3FDqGCmGJ8AOvjoLIz3QoGaJxB9Y@0kP2f3YyjZlf1Nw "Java (JDK 10) – Try It Online")
[Answer]
# Sed, 17 Bytes
`:;s/[0-9]\+,0//;t`
-3 bytes thanks to @OMᗺ, -1 thanks to @eggyal
Because you're guaranteed to never pop an empty list, you don't need anything more than an iterated finite state machine. Regular expressions are a tool for building finite state machines, and `sed` can iterate. It's a match made in heaven.
Takes input from stdin, like so:
`echo '[12,3,0,101,11,1,0,0,14,0,28]' | sed ':;s/[0-9]\+,0,//;t'`
Outputs the stack in reverse:
`[12,101,28]`
Could be smaller by two bytes if my local `sed` inherently understood character classes like `\d`, but it doesn't for some reason.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~46~~ ~~41~~ 40 bytes
```
$args|%{$x,$a=&({1,$_+$a},{$a})[!$_]};$a
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24RrVapUJHJdFWTaPaUEclXlslsVanGkhoRiuqxMfWWqsk/v//39Dov/F/g/@GBob/DYEIyARyTICEkQUA "PowerShell – Try It Online")
Takes input via splatting, e.g., `$z=@(12,3,0,101,11,1,0,0,14,0,28); .\implement-stack.ps1 @z`, which on TIO manifests as separate arguments.
```
$args|%{$x,$a=&({1,$_+$a},{$a})[!$_]};$a    # Full program
$args                                       # Take input via splatting
     |%{                            };      # Loop through each item
              &(              )[!$_]        # Pseudo-ternary, if input is 0 this is 1
        $x,$a=            {$a}              # ... which will pop the first item into $x
           $a=  { ,$_+$a}                   # Else, we append the first item
        $x   =   1                          # ... and drop a dummy value into $x
                                      $a    # Leave $a on pipeline; implicit output
```
*-5 bytes thanks to mazzy.*
*-1 byte swapping `$_` to `1`*
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~62~~ ~~60~~ ~~56~~ 55 bytes
~~-2~~ -6 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)
-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
Uses the permitted notion of -1 terminated arrays. `f()` calls itself recursively, until fully wound, and then backtracks through the list. `r` keeps track of how many numbers to discard before printing something. Increases if current item is 0, decreases otherwise. If 0, we need not discard, and can print the number.
```
r;f(int*l){~*l?f(l+1),*l?r?r--:printf("%d ",*l):r++:0;}
```
[Try it online!](https://tio.run/##bY7fCoMgFMav11MchIGWglrCSEYPMnYx2hpBizB3Fe3Vm/aXoAv1nN/5vuOXs3eeD4PRBS5rG1ak@4VVVuAqEoS6ymSGsbQxblhgdH4CcpSkJopSrvvBYfg8yhqToAuCk2/tq7W3O1yhE5JCTIFTEFy4y5@x9SQZH3mhwESvN6ucvW42KqYFk3qvjCflBDecrAv2cjXzOVHsUy2BBOeKglrCrV8FpwJ7L9HQfG2LESJ6YfIIxkcwOYLKlf3wBw "C (gcc) – Try It Online")
[Answer]
## Haskell, 28 bytes
```
foldl(#)[]
(_:s)#0=s
s#n=n:s
```
[Try it online!](https://tio.run/##RUztCgIhEPx/TyH4R2ELPzo6DnyEnsAk5Mo68kyy589W/8QyzM7O7Dx8ed5irIEYcq7hFa@RUW7dwC5z4VSYMhSaTJpL3fyaMLX5fCIsv9f0IXsSOLHWgZUNIEAhH5AlyLZOoHFVoLut4YgWTlO6pdBtWYQQI4x/F1/6FXtkD6BovWpyrn6XEP291N2S8w8 "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ṣ0Ṗ;¥/
```
[Try it online!](https://tio.run/##y0rNyan8///hzsUGD3dOsz60VP//4fZHTWvc//@Pjo7V4VKINoSQOgY6RmCWCZBlqGMI4VjoGAM5RjrGUEXGOuZAaSCE8I1BaoEqQDqA2MDAVMcUWR6oESwONM8QrATIAZlvZBEbCwA "Jelly – Try It Online")
### How it works
```
ṣ0Ṗ;¥/  Main link. Argument: A (array)
ṣ0      Split A at zeroes.
    ¥/  Left-reduce the resulting 2D array by this dyadic chain:
  Ṗ       Pop; discard the last element of the left argument.
   ;      Concatenate the result with the right argument.
```
[Answer]
# [R](https://www.r-project.org/), 45 bytes
```
o={};for(e in scan())o="if"(e,c(e,o),o[-1]);o
```
[Try it online!](https://tio.run/##K/r/P9@2utY6Lb9II1UhM0@hODkxT0NTM99WKTNNSSNVJxmI8zV18qN1DWM1rfP/GxpxGXMZcBkaGHIZAhGQCeSYAAkji/8A "R – Try It Online")
* -4 byte thanks to @Giuseppe
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
#//.{a___,b_,0,c___}:>{a,c}&
```
[Try it online!](https://tio.run/##TYzNCgIxDITveY3CohDtn4uL4rKP4F2k1OLiHtaD9Fb67HVaLxISvmRmsvr4eq4@LsGX@bIpQsp98s45fjhWHED5NCbPIXdle6brZ3nHm9iN8yTunZwSUcpMSbeBhKlwAGjWjQe2YMP257B8hIhqq61G6NWOVqrn/k9Gqp3xSzcHlvrbDJkoly8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~59~~ ~~57~~ 51 bytes
```
s=[]
for x in input():s=(s+[x],s[:-1])[x<1]
print s
```
[Try it online!](https://tio.run/##DYdBCoAgEADvvcKj0QatdQjJlyx7jbyouAb2elsYhpnytScnN4YE4unO1XQTk1LeZmcvwcpCnUHIr8gz9Qt5KjWmZmQMQgc7bIAbAiqaOofKnfwD "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
s=[]
for x in input():s=([x]+s)[2*0**x:]
print s
```
[Try it online!](https://tio.run/##VY1BCsMgEEX3OcXgKrEu1DQ0CDmJuCqWCMVItNSe3jpKF4Vx@H/m/TF80n54Wd67e1oQymZ7J4SUuGkzPI4TMjhfK7zSOKm4jTqbS5y0pJzSrMwQTucTxIKhGtECHwPOQFZ1bap6gW5lMDcnq@hc9bfGYOFo7gnkehI75wuD5Y@TLduWeF78WJz0X@Vqvg "Python 2 – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~40~~ 36 bytes
```
([]){{}{({}<>)<>}([]){{}<>}{}([])}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZao7rWxk7Txq4WKgBkVYPZQNb//4ZGCsYKBgqGBoYKhkAEZAI5JkDCyAIA "Brain-Flak – Try It Online")
Thanks to @Nitrodon for -4 bytes.
Since Brain-Flak already uses stacks, this is a good puzzle for Brain-Flak.
```
([]){   while items on stack
    {}      pop stack count
    {       if top element is non-zero
        ({}<>)<> push it on the other stack
    }
    if we're here the stack is either empty or there's a 0 on the stack
    ([])    so, count the stack again
    {{}<>{}<>} if there are items left on the stack, pop the stack count and the last item of the other stack
    {} pop the zero or the stack count
    ([]) count the stack again for next round
}
<>  go to the output stack
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 89 bytes
```
[N
S S N
_Create_Label_LOOP_1][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input][N
T   T   S
_If_neg_Jump_to_Label_EXIT][S N
S _Duplicate_input][N
T   S T N
_If_0_Jump_to_Label_DROP][N
S N
N
_Jump_to_Label_LOOP_1][N
S S S N
_Create_Label_EXIT][S N
N
_Discard_top][N
S S S S N
_Create_Label_LOOP_2][T N
S T _Print_as_integer][S S S T  S T S N
_Push_10_newline][T N
S S _Print_as_character][N
S T S S N
_Jump_to_Label_LOOP_2][N
S S T   N
_Create_Label_DROP][S N
N
_Discard_top][S N
N
_Discard_top][N
S N
N
_Jump_to_Label_LOOP_1]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
Takes the input-list new-line separated with `-1` to indicate we're done with the inputs.
[Try it online](https://tio.run/##LYrLCYBADETPO1VsA8JGPdiOyILeBAXLjy/RkGS@z37c/TrXrburVpZTLSoxwb8PYgL6K4m4dEHC5DVlZCU6WZPcbdSkJmsmY6GImTcuGuwF).
**Explanation in pseudo-code:**
```
Start LOOP_1:
  Integer i = STDIN as integer
  If(i is negative):
    Call function EXIT
  If(i is 0):
    Call function DROP
  Go to next iteration of LOOP_1
function EXIT:
  Start LOOP_2:
    Pop and print top as integer
    Print newline
    Go to next iteration of LOOP_2
function DROP:
  Drop the top of the stack
  Go to next iteration of LOOP_1
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ ~~59~~ ~~57~~ 56 bytes
```
l=input()
while 0in l:i=l.index(0);l[i-1:i+1]=[]
print l
```
[Try it online!](https://tio.run/##RYzPCsIwDMbvfYqy06ZR@sdhmfSknn2AspMWFih1SMX59DXZRULIl/y@fPO3TM9s6vl2ufqmaWrymOd3aTvxmTBFqTDLNKBPe8yPuLSqO6WAOz3gVo8@jGJ@YS4yVXoWIi7xLjlr4yqxoLlBgaF5oKlBs3RgSRqwK7ZwJETFm2UXUfZSK9VD/6f0sl4pR68GWjjXuPEH "Python 2 – Try It Online")
---
Saved:
* -1 byte, thanks to pushkin
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~214~~ 150 bytes
```
>>,[>++++++[-<-------->]+<[>+++++[-<++++++++>]]>[-<<<[[-]<],[-]>>>>-<<]>>+[<<+<,----------[++++++++++>-]>[->>-<]>[->+<]>]<<<,]<<[[<]++++++++++<]>>[.>]
```
Reads input as numbers separated by newlines. This must include a single trailing newline. Also expects no leading zeros on each number. Output as a similar newline separated list
[Try it online!](https://tio.run/##RYzBCsNACETv/opryaY95CD@iMwhCRRKoYdAv387G5b0IY4OOtuxvj7P7/5uLaJk6Ema2yCgPmy6OggguLpnGhyFPQgdqqa7erGL1Iuw/tgvT1UKGFPQoxz/wx6Ut0BrdZa7TFKnKpXFkcuDbV7kBw "brainfuck – Try It Online")
# Explanation ~~that isn't really an explanation but is actually just the version I was working on with the comments and stuff which may or may not actually be useful to anyone~~
```
Stack format:
0 (0 \d*)*
>>,[
    Setup digit == '0' conditional
    >++++++
    [-<-------->]
    +
    <[
        Read digit != '0'
        Restore the char code
        cond1 is already 1 at this stage
        >+++++
        [-<++++++++>]
    ]>[
        Read digit == '0'
        -
        Pop previous value
        <<<[
            [-]<
        ]
        Skip next input (assumed to be newline)
        ,[-]
        Skip following loop by unsetting loop flag
        >>>>-
        <<
    ]

    Move to next stack frame
    >
    Set loop flag
    >+[
        Set bit used for conditional
        <<+
        Read next character
        <,
        Compare with '\n'
        ----------[
            Not '\n': restore the char code
            ++++++++++

            >-
        ]>[
            -
            == '\n': Leave as 0
            Unset loop flag
            >>-
            <
        ]

        Copy loop flag along
        >
        [- > + <]

        Move to loop flag of next stack frame
        >
    ]

    <<<
,]
Fill in with newlines
<<[
    Skip to the cell before this value
    [<]
    Put a newline in there
    ++++++++++
    Move to next value
    <
]
Now the tape has the exact values we need to output
>>[.>]
```
[Answer]
# JavaScript, 40 bytes
Outputs in reverse order.
```
a=>a.map(x=>x?o.push(x):o.pop(),o=[])&&o
```
[Try it online](https://tio.run/##VZBPj8IgEMXP@ik8GUhGLKDZZpN27x7Wg0dsInGpW@MyTVHT/fR1qP8hJPB7bx6T2duzDdumqo8Tjz@uK7POZrkVf7ZmbZa3XyjqU/hlLf@kG9aMA2am4OMxdlv0AQ9OHHDHzNAUMKA1nY4m@cgUQyPfgIwEElA9vUFFcEZQgnzjUkH0p6BJUqBfNU1AkpD2gRo@qJ72qyUqOsZSeQynkyRzmD@c9290dFJ@76AmZG@mR2xKpU@nSq8Gari4z2axWn6LcGwqv6vKf1bSjETjzq4JjnHOxR4rv1n7De8u)
1 byte saved thanks to [Herman L](https://codegolf.stackexchange.com/users/70894/herman-l).
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 32 bytes
```
([]){{}{({}<>)<>}{}<>{}<>([])}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZao7rWxk7Txq4WRIMwSAJI/f9vaKRgrGCgYGhgqGAIREAmkGMCJIwsFHQNAQ "Brain-Flak – Try It Online")
Uses `-1` to signify the end of the array (but any number will do really).
[Answer]
# [V](https://github.com/DJMcMayhem/V), 10 bytes
```
ò/ 0⏎b2dw0
```
[Try it online!](https://tio.run/##K/v///AmfQUDriSjlHKD//8NDRQMFQyA0FjBVMEAAA "V – Try It Online")
### Explanation
```
ò           " run the following, until an error occurs
 / 0⏎       " | goto next zero with space in front (errors if none)
     b      " | jump one word back (to the beginning of element to pop)
      2     " | twice (element & zero itself)
       dw   " | | delete word
         0  " | goto beginning of line
```
---
## Equivalent in [Vim](https://www.vim.org/), 16 bytes
```
qq/ 0⏎b2dw0@qq@q
```
[Try it online!](https://tio.run/##K/v/v7BQX8GAK8kopdzAobDQofD/f0MDBUMFAyA0VjBVMAAA "V – Try It Online")
### Explanation
Pretty much the same, except recording a macro `q` and recursively call it:
```
qq                " record macro q
  / 0⏎b2dw0       " same as in V
           @q     " recursively call q (aborts on error)
             q    " quit recording
              @q  " execute the macro q
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes
```
~c₃Ckt[İ,0]≠∧C⟨hct⟩↰|
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3wvy75UVOzc3ZJ9JENOgaxjzoXPOpY7vxo/oqM5JJH81cC1db8/x@tEB2roxBtCCZ0DHSMQAwTIMNQxxDMttAxBrKNdIwhKox1zIGSQAjmGoMUAuVByoHYwMBUxxRJGqgLLAw0yxCsAsgBmW1kERsLAA "Brachylog – Try It Online")
-1 byte, and more importantly this feels like a much less clunky way of doing this.
```
~c₃                     % Partition the input into 3 subarrays
   C                    % Call that array-of-arrays C
    kt[İ,0]             % Its second element should be of the form [Integer, 0]
           ≠            % And its elements shouldn't be equal (i.e.
                        %   the Integer shouldn't be 0)
            ∧C⟨hct⟩     % Then, remove that [İ, 0] element from C
                   ↰    % And call this predicate recursively
                    |   % When the above fails (when it can't find a partition with
                        %  [İ, 0] in it), then just output the input
```
Alternate 21 byter: `∋0∧ℕ₁;0;P↺c;Qc?∧P,Q↰|` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3w/1FHt8GjjuWPWqY@amq0NrAOeNS2K9k6MNkeKBigEwhUXPP/f7RCdKyOQrQhmNAx0DECMUyADEMdQzDbQscYyDbSMYaoMNYxB0oCIZhrDFIIlAcpB2IDA1MdUyRpoC6wMNAsQ7AKIAdktpFFbCwA "Brachylog – Try It Online")
---
Older code:
**22 bytes**
```
∋0&b,1;?z{=|¬∋0&}ˢtᵐ↰|
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FHt4Fako6htX1VtW3NoTVgfu3pRSUPt0541Lah5v//aENjHQMdIGEIJEEsAwNTHVMgAwhj/0cBAA "Brachylog – Try It Online")
```
∋0           If input contains a 0,
&b           Remove input's first element, getting list of "next" elements
,1           Append 1 to that to handle last element
;?z          Zip that with input
{      }ˢ    Select only zipped pairs where
 =|          both elements are equal (to keep 0s followed by 0s)
   ¬∋0&      or the pair doesn't contain a 0
             this removes both the (pairs containing the) value
              that is followed by a 0, and the 0 itself
tᵐ           Recover back the (filtered) input array elements from the zip
↰            Call this predicate recursively
|            If input contains no 0s, input is the output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
vy>i¨ëy)˜
```
[Try it online](https://tio.run/##MzBNTDJM/f@/rNIu89CKw6srNU/P@f8/2tBIx1jHQMfQwFDHEIiATCDHBEgYWcQCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7JKu8xDKw6vrtQ8Ped/ba3O/2jDWK5oQx0DHSMgbaFjrGOoY6RjDBYz1jEHigMhiGcMZAAJQyAJYhkYmOqYImSBWsCihjqGhmAFQI4JyFALoKxBLAA).
**Explanation:**
```
v        # For-each of the items in the input-list:
 y>i     #  If the current item is 0:
  ¨      #   Pop the top item of the list
 ë       #  Else:
  y      #   Push the current item to the stack
   )     #   Wrap the entire stack into a list
         #    i.e. 12 → [12]
         #    i.e. [12] and 3 → [[12], 3]
    ˜    #   Flatten the stack
         #    i.e. [[12], 3] → [12, 3]
         # (and output the list implicitly after the loop)
```
---
**9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative:**
```
vy_i\ëy])
```
[Try it online](https://tio.run/##MzBNTDJM/f@/rDI@M@bw6spYzf//ow2NdIx1DHQMDQx1DIEIyARyTICEkUUsAA) of [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7LK@MyYw6sra2s1/@v8jzaM5Yo21DHQMQLSFjrGOoY6RjrGYDFjHXOgOBCCeMZABpAwBJIgloGBqY4pQhaoBSxqqGNoCFYA5JiADLUAyhrEAgA).
**Explanation:**
```
v        # For-each of the items in the input-list:
 y_i     #  If the current item is 0:
  \      #   Discard top item of the stack
 ë       #  Else:
  y      #   Push the current item to the stack
]        # Close both the if-else and for-each (short for `}}`)
 )       # Wrap the entire stack into a list (and output implicitly)
```
PS: If the output should have been reversed to match the test cases in the challenge description, we can add a trailing `R` to the second version (so **10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**), which reverses the list. [Try it online](https://tio.run/##MzBNTDJM/f@/rDI@M@bw6spYzaD//6MNjXSMdQx0DA0MdQyBCMgEckyAhJFFLAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7LK@MyYw6sra2s1g/7r/I82jOWKNtQx0DEC0hY6xjqGOkY6xmAxYx1zoDgQgnjGQAaQMASSIJaBgamOKUIWqAUsaqhjaAhWAOSYgAy1AMoaxAIA).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 18 bytes
```
^
,
+1`,\d+,0
^,
```
[Try it online!](https://tio.run/##NYzBCoAwDEPv@Q4FYTmsm6J/4NEfkDFBD148iP8/M0FKS5OX9j6e89pK2825JBDOMtfd0QOJwJKaLFkKDEbPgF7TaAETo5bAKBA5ylbBYuUiNaX2fuDwM4U/T/f2YYn6L0wv "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^
,
```
Prefix an extra `,`.
```
+1`,\d+,0
```
Process all pop operations.
```
^,
```
Remove the `,` if it's still there.
Reversing the numbers would cost an extra 8 bytes:
```
O^$`\d+
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->a{b=[];a.map{|x|x>0?b<<x:b.pop};b}
```
[Try it online!](https://tio.run/##VY7RCsIwDEXf9xUDX7PRtA6L2@qHlD604vBFLGPCZO2313SyoZRA78nNTcaXe6ehT5Wyi@u1aW39sH4Jc5gVu7ium8@u9k8fWxeTLrQp4VCpUptC4/bHLIAB3wAncCSAgDtDDtknQRDmIDYuSCBBuYYIONEcvd89IkfRWA6kYqyB5t@FIvsode3TWlytJPIZXO6HyW@bDjT1zV7vS5iCLwc9mZg@ "Ruby – Try It Online")
Anonymous lambda. Outputs in reverse order.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes
```
([]){{}{(({}<>))(<>)}{}<>{}<>([])}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZaQ6O61sZOU1MDSNSCmCAMkgRS//8bGikYKxgoGBoYKhgCEZAJ5JgACSMLAA "Brain-Flak – Try It Online")
```
#Let's call the two stacks in and out
([]){{}                      ([])}    # while not in.empty()
       {        (  )}{}               # if in.peek() != 0
        (({}<>)) <>                   # a = in.pop; out.push(a); out.push(a)
                       <>{}<>         # out.pop()
                                  <>  # switch to out to be printed
```
[Answer]
# Java 10, ~~75~~ 72 bytes
```
n->{var s="";for(int i:n)s=(s+","+i).replaceAll(",\\d+,0","");return s;}
```
Outputs separated by a comma. Top of the stack is last. Try it online [here](https://tio.run/##tVPLbtswELz3KxY8UTAjWHKDGhEcwEBbIEiLHnKMe2BkOqBDUy6XchIY@nZ3SUmuhR6qSymI4mN2ZpcabuVBXm3XL6d9/WR0CaWRiPBdagvHD0BNW6/cRpYKHrwsX7rV0B680/YZ9q4qFSIn4ONPsPXuSTlMighrYt9Ro5eePodKr2FHArwloCDpnjEZMAcljP0CTvbq9niQDnDBWLGpXJACfWMTXHCcMMEmOkmd2hvKcmkMZ2K1Wk/ElHZYUjjla2cBi@bU8xdnJa/Q8ygkwKpXaIs4NgJC6L9gWcCJbAxSTEUe0fkI9EdCZyJrA8JgRMxczAiai1kMOs9G5TYTn0iRnrF1z0KCpBDSpHc6vRbXfxhoawwJZReDqcAs8tAkVJ7PW5I87uVzNjST0wfp1cBNUeHCNAIGZhS9VdXbXpVerZO/XSxLX0tDbosEaW/qoZ3jfdjwniZVvygGeRubXLJG5nf0apdWtSc6SshYvqXbltZem3TpnHzH1Fet/lkIJsBgcQsrxmjYZUVrKwb8x31yea4NKIPqf4t@Xd59@/JZnM/upkP18xY3TKz7Xc3pNw).
Thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for golfing 2 bytes.
Please check out [Kevin Cruijssen's](https://codegolf.stackexchange.com/a/169361/79343) and [Olivier Grégoire's](https://codegolf.stackexchange.com/a/169423/79343) Java answers as well. They take a list-based approach instead, with the latter beating mine by a tidy margin.
Ungolfed:
```
n -> { // lambda taking an integer array as argument and returning a String
    var s = ""; // we'll be using a String to implement and output the stack
    for(int i : n) // loop through the array
        s = (s + "," + i) // append the next number
               .replaceAll(",\\d+,0", ""); // remove any number followed by a zero
    return s; // output the resulting stack
}
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), ~~14~~ 12 bytes
```
~{.{;}if}/]`
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPmfp1r9v65ar9q6NjOtVj824X@tap7W/@hYBa5oQzChYKBgBGKYABmGCoZgtoWCMZBtpGAMUWGsYA6UBEIw1xikECgPUg7EBgamCqZI0kBdYGGgWYZgFUAOyGwji1gA "GolfScript – Try It Online")
```
~{.{;}if}/]` Full program, implicit input
~            Eval input
 {      }/   Foreach:
      if       If the value is truthy (!= 0):
  .              Push itself
   {;}         Else: pop the top value
          ]` Push as array representation
             Implicit output
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 17 bytes
*Thanks @sundar and @DomHastings*
```
s/\d+ 0 ?//&&redo
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPyZFW8FAwV5fX02tKDUl//9/QyMFY6CIoYGhgiEQAZlAjgmQMLJQMPiXX1CSmZ9X/F/X11TPwNDgv24BAA "Perl 5 – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 25 bytes
```
i:?\~~
(0:/:^?
!?l:!<oan;
```
[Try it online!](https://tio.run/##S8sszvj/P9PKPqaujkvDwErfKs6eS9E@x0rRJj8xz/r/fwA "><> – Try It Online") (input must be written in ascii. otherwise use [this one](https://fishlanguage.com/))
### How it works
`i:?\~~` checks for 0, continues to `~~` to delete previous entry. otherwise go down to:
`(0:/:^?` which checks for -1 (no more input), then wrap up to delete -1 and loop:
`!?l:!<oan;` which outputs each number with a newline, then ends when stack emptied
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
Since there's no Husk answer already and it's my favourite golfing-lang:
```
F`?:tø
```
[Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/rsl2FuVHN7x////6FiuaEMQ1jHQMQLSJkDaUMcQxLTQMQYyjXSMwdLGOuZAKSAE8YxBqoCyILVAbGBgqmOKkAVqAYsCzTEEKwByQOYaWcQCAA "Husk – Try It Online")
### Explanation
```
F`?:tø  --
F    ø  -- foldl (reduce) with [] as the initial accumulator
 `      -- | flip arguments of
  ?:    -- | | if truthy: apply cons (prepend) to it
    t   -- | | else: return tail
        -- | : returns a function, either prepending the element or dropping 1 element
```
### Alternative solution, 6 bytes
Instead of flipping, we can also just reverse the list and then use a right-fold: [`Ḟ?:tø↔`](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/j/cMc/equTwjkdtU/7//x8dyxVtCMI6BjpGQNoESBvqGIKYFjrGQKaRjjFY2ljHHCgFhCCeMUgVUBakFogNDEx1TBGyQC1gUaA5hmAFQA7IXCOLWAA "Husk – Try It Online")
[Answer]
***Warning:*** Lots of lines ensue. You have been warned.
---
# [CJam](https://sourceforge.net/projects/cjam/), 17 bytes
**Most dangerous code**
(Assumes the stack elements can be separated by only spaces in the output and that the input array can be whatever form we wish)
```
q~{X0={;}X?}fX]S*
```
[Try it online!](http://cjam.aditsu.net/#code=q%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5DS*&input=%5B1%200%201%201%5D)
*Explanation*
```
q                                    Reads input string
 ~                                   Instantly convert to array since the string is in the CJam format
  {        }fX                       For loop
   X0=                               If X (the array element currently being checked) is equal to 0
      {;}                            Pop the top element from the stack
         X                           Else push X onto the top of the stack
          ?                          If-Else flag
              ]                      Collate all stack elements into an array
               S*                    Put a space between each array element
```
---
**Alternate Code #1, 27 bytes**
(Assumes stack elements have to be output in the format shown in the question and that the input array can be whatever form we wish)
```
q~{X0={;}X?}fX]',S+*'[\+']+
```
[Try it online!](http://cjam.aditsu.net/#code=q%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5D%27%2CS%2B*%27%5B%5C%2B%27%5D%2B&input=%5B1%200%201%201%5D)
*Explanation*
```
q                                    Reads input string
 ~                                   Instantly convert to array since the string is in the CJam format
  {        }fX                       For loop
   X0=                               If X (the array element currently being checked) is equal to 0
      {;}                            Pop the top element from the stack
         X                           Else push X onto the top of the stack
          ?                          If-Else flag
              ]                      Collate stack items into an array
               ',S+                  Add together a comma and a space to create a delimiter
                   *                 Apply the delimiter to the stack
                    '[\+             Append left bracket to the left of the stack text
                        ']+          Append right bracket to the right of the stack text
```
---
**Alternate Code #2, 24 bytes**
(Assumes the stack elements can be collated in the output and that the input array has to be in the exact format shown in the question)
```
q',/~]S*~{X0={;}X?}fX]S*
```
[Try it online!](http://cjam.aditsu.net/#code=q%27%2C%2F%7E%5DS*%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5DS*&input=%5B1%2C0%2C1%2C1%5D)
*Explanation*
```
q                        Read input string
 ',/                     Separate by commas (since commas are an invalid array delimiter in CJam)
    ~                    Turn string into an array of substrings that make up the array
     ]S*                 Add spaces in between input numbers to prevent collation in the array
        ~                Turn the string into a valid array representative of the original
         {        }fX    For loop
          X0=            If X (the array element currently being checked) is equal to 0
             {;}         Pop the top element from the stack
                X        Else push X onto the top of the stack
                 ?       If-Else flag
                     ]   Collate all stack elements into an array
                      S* Add a space between each element
```
---
**Safest code for this, 34 bytes**
(Assumes stack elements have to be output in the format shown in the question and that the input array has to be in the exact format shown in the question)
```
q',/~]S*~{X0={;}X?}fX]',S+*'[\+']+
```
[Try it online!](http://cjam.aditsu.net/#code=q%27%2C%2F%7E%5DS*%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5D%27%2CS%2B*%27%5B%5C%2B%27%5D%2B&input=%5B1%2C0%2C1%2C1%5D)
*Explanation*
```
q                                      Read input string
 ',/                                   Separate by commas (since commas are an invalid array delimiter in CJam)
    ~                                  Turn string into an array of substrings that make up the array
     ]S*                               Add spaces in between input numbers to prevent collation in the array
        ~                              Turn the string into a valid array representative of the original
         {        }fX                  For loop
          X0=                          If X (the array element currently being checked) is equal to 0
             {;}                       Pop the top element from the stack
                X                      Else push X onto the top of the stack
                 ?                     If-Else flag
                     ]                 Collate stack items into an array
                      ',S+             Add together a comma and a space to create a delimiter
                          *            Apply the delimiter to the stack
                           '[\+        Append left bracket to the left of the stack text
                               ']+     Append right bracket to the right of the stack text
```
---
Thanks to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for pointing out that the ones with the collated output are invalid since things like `[12]` and `[1,2]` would be indistinguishable.
Thanks also to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) providing a very suitable alternative for the collated outputs and cutting off 9 bytes!
[Answer]
# [Red](http://www.red-lang.org), 64 bytes
```
func[b][a: copy[]foreach n b[either n > 0[insert a n][take a]]a]
```
[Try it online!](https://tio.run/##ZU1BCsMwDLvvFXpC0qys9LBH7Gp8SFuHlkFasuzQ12duDyNjGIMkS3KSqTxkIr6EvoR3HGlg8j3GdduJw5rEjzMiBpIlz5IU3mFoiS9JGR6RKfunwDN7LltaYkaA1n2hrTEMmopflVvYWurgVGrgfmION7Xq1Ko70uo@OnSNadH@u7TqvOofexqVHH@bjssH "Red – Try It Online")
]