title: Swap the parity

text:
# Question
Title: Swap the parity
# Task

Given a positive integer `n`, output `n+1` if `n` is odd, and output `n-1` if `n` is even.

# Input

A positive integer. You may assume that the integer is within the handling capability of the language.

# Output

A positive integer, specified above.

# Testcases

```
input output
    1      2
    2      1
    3      4
    4      3
    5      6
    6      5
    7      8
    8      7
  313    314
  314    313

```

# Scoring

This is , so shortest answer in bytes wins.

Standard loopholes apply.

# References

# Answer
# C, 20 bytes

```
f(x){return-(-x^1);}

```

Try it online.
> 29 votes

# Answer
## Stack Cats, 3 + 3 (`-n`) = 6 bytes

```
-*-

```

Try it online!

Needs the `-n` flag to work with numeric input and output.

### Explanation

Stack Cats is usually far from competitive, because of its limited set of commands (all of which are injections, and most of which are involutions) and because every program needs to have mirror symmetry. However, one of the involutions is to toggle the least-significant bit of a number, and we can offset the value with unary negation which also exists. Luckily, that gives us a symmetric program, so we don't need to worry about anything else:

```
-   Multiply the input by -1.
*   Toggle the least significant bit of the value (i.e. take it XOR 1).
-   Multiply the result by -1.

```

Input and output are implicit at the beginning and end of the program, because taking input and producing output is not a reversible operation, so they can't be commands.
> 23 votes

# Answer
# x86 Assembly, 9 bytes (for competing entry)

Everyone who is attempting this challenge in high-level languages is missing out on the *real* fun of manipulating raw bits. There are so many subtle variations on ways to do this, it's insane—and a lot of fun to think about. Here are a few solutions that I devised in 32-bit x86 assembly language.

I apologize in advance that this isn't the typical code-golf answer. I'm going to ramble a lot about the thought process of iterative optimization (for size). Hopefully that's interesting and educational to a larger audience, but if you're the TL;DR type, I won't be offended if you skip to the end.

The obvious and efficient solution is to test whether the value is odd or even (which can be done efficiently by looking at the least-significant bit), and then select between *n+1* or *n−1* accordingly. Assuming that the input is passed as a parameter in the `ECX` register, and the result is returned in the `EAX` register, we get the following function:

```
F6 C1 01  |  test  cl, 1                      ; test last bit to see if odd or even
8D 41 01  |  lea   eax, DWORD PTR [ecx + 1]   ; set EAX to n+1 (without clobbering flags)
8D 49 FF  |  lea   ecx, DWORD PTR [ecx - 1]   ; set ECX to n-1 (without clobbering flags)
0F 44 C1  |  cmovz eax, ecx                   ; move in different result if input was even
C3        |  ret

```

**(13 bytes)**

But for code-golf purposes, those `LEA` instructions aren't great, since they take 3 bytes to encode. A simple `DEC`rement of `ECX` would be much shorter (only one byte), but this affects flags, so we have to be a bit clever in how we arrange the code. We can do the decrement *first*, and the odd/even test *second*, but then we have to invert the result of the odd/even test.

Also, we can change the conditional-move instruction to a branch, which may make the code run more slowly (depending on how predictable the branch is—if the input alternates inconsistently between odd and even, a branch will be slower; if there's a pattern, it will be faster), which will save us another byte.

In fact, with this revision, the entire operation can be done in-place, using only a single register. This is great if you're inlining this code somewhere (and chances are, you would be, since it's so short).

```
    48     |  dec  eax          ; decrement first
    A8 01  |  test al, 1        ; test last bit to see if odd or even
    75 02  |  jnz  InputWasEven ; (decrement means test result is inverted)
    40     |  inc  eax          ; undo the decrement...
    40     |  inc  eax          ; ...and add 1
  InputWasEven:                 ; (two 1-byte INCs are shorter than one 3-byte ADD with 2)

```

**(inlined: 7 bytes; as a function: 10 bytes)**

But what if you did want to make it a function? No standard calling convention uses the same register to pass parameters as it does for the return value, so you'd need to add a register-register `MOV` instruction to the beginning or end of the function. This has virtually no cost in speed, but it does add 2 bytes. (The `RET` instruction also adds a byte, and there is a some overhead introduced by the need to make and return from a function call, which means this is one example where inlining produces both a speed *and* size benefit, rather than just being a classic speed-for-space tradeoff.) In all, written as a function, this code bloats to 10 bytes.

What else can we do in 10 bytes? If we care at all about performance (at least, *predictable* performance), it would be nice to get rid of that branch. Here is a branchless, bit-twiddling solution that is the same size in bytes. The basic premise is simple: we use a bitwise XOR to flip the last bit, converting an odd value into an even one, and vice versa. But there is one niggle—for odd inputs, that gives us *n-1*, while for even inputs, it gives us *n+1*— exactly opposite of what we want. So, to fix that, we perform the operation on a negative value, effectively flipping the sign.

```
8B C1     |  mov eax, ecx   ; copy parameter (ECX) to return register (EAX)
          |
F7 D8     |  neg eax        ; two's-complement negation
83 F0 01  |  xor eax, 1     ; XOR last bit to invert odd/even
F7 D8     |  neg eax        ; two's-complement negation
          |
C3        |  ret            ; return from function

```

**(inlined: 7 bytes; as a function: 10 bytes)**

Pretty slick; it's hard to see how that can be improved upon. One thing catches my eye, though: those two 2-byte `NEG` instructions. Frankly, two bytes seems like one byte too many to encode a simple negation, but that's the instruction set we have to work with. Are there any workarounds? Sure! If we `XOR` by -2, we can replace the second `NEG`ation with an `INC`rement:

```
8B C1     |  mov eax, ecx
          |
F7 D8     |  neg eax
83 F0 FE  |  xor eax, -2
40        |  inc eax
          |
C3        |  ret

```

**(inlined: 6 bytes; as a function: 9 bytes)**

Another one of the oddities of the x86 instruction set is the multipurpose `LEA` instruction, which can do a register-register move, a register-register addition, offsetting by a constant, and scaling all in a single instruction!

```
8B C1        |  mov eax, ecx
83 E0 01     |  and eax, 1        ; set EAX to 1 if even, or 0 if odd
8D 44 41 FF  |  lea eax, DWORD PTR [ecx + eax*2 - 1]
C3           |  ret

```

**(10 bytes)**

The `AND` instruction is like the `TEST` instruction we used previously, in that both do a bitwise-AND and set flags accordingly, but `AND` actually updates the destination operand. The `LEA` instruction then scales this by 2, adds the original input value, and decrements by 1. If the input value was odd, this subtracts 1 (2×0 − 1 = −1) from it; if the input value was even, this adds 1 (2×1 − 1 = 1) to it.

This is a very fast and efficient way to write the code, since much of the execution can be done in the front-end, but it doesn't buy us much in the way of bytes, since it takes so many to encode a complex `LEA` instruction. This version also doesn't work as well for inlining purposes, as it requires that the original input value be preserved as an input of the `LEA` instruction. So with this last optimization attempt, we've actually gone backwards, suggesting it might be time to stop.

---

Thus, for the final competing entry, we have a 9-byte function that takes the input value in the `ECX` register (a semi-standard register-based calling convention on 32-bit x86), and returns the result in the `EAX` register (as with all x86 calling conventions):

```
           SwapParity PROC
8B C1         mov eax, ecx
F7 D8         neg eax
83 F0 FE      xor eax, -2
40            inc eax
C3            ret
           SwapParity ENDP

```

Ready to assemble with MASM; call from C as:

```
extern int __fastcall SwapParity(int value);                 // MSVC
extern int __attribute__((fastcall)) SwapParity(int value);  // GNU

```
> 14 votes

# Answer
# Jelly, 3 bytes

```
-*ạ

```

Try it online!

Pseudocode: `abs((-1)**n - n)`
> 12 votes

# Answer
# Python3, ~~20~~ 18 bytes

```
lambda n:n-1+n%2*2

```

Pretty simple. First we calculate **n-1** and decide whether to add 2 to it, or not.

**If n is even** --\> **n mod 2** will be 0, thus we'll add **2\*0** to **n-1**, resulting in **n-1**.

**If n is odd** --\> **n mod 2** will be 1, thus we'll add **2\*1** to **n-1**, resulting in **n+1**.

I prefer an explanation that I made with MS paint & a laptop touchpad...
> 12 votes

# Answer
# Python, 16 bytes

```
lambda x:-(-x^1)

```

Try it online!
> 12 votes

# Answer
# MATL, 7 bytes

```
Q:HePG)

```

This avoids any arithmetical operations. Try it online!

### Explanation

Consider input `4` as an example.

```
Q    % Implicit input. Add 1
     % STACK: 5
:    % Range
     % STACK: [1 2 3 4 5]
He   % Reshape with 2 rows in column-major order. Pads with a zero if needed
     % STACK: [1 3 5;
               2 4 0]
P    % Flip vertically
     % STACK: [2 4 0;
               1 3 5]
G    % Push input again
     % STACK: [2 4 0;
               1 3 5], 4
)    % Index, 1-based, in column major order. Implicitly display
     % STACK: 3

```
> 10 votes

# Answer
# Braingolf v0.1, ~~11~~ 10 bytes

```
.1>2,%?+:-

```

Try it online! (Second argument is the Braingolf code, third argument is the input)

Saved a byte thanks to Neil

First ever competing braingolf answer :D

Explanation:

```
.            Duplicate the top of the stack
 1>          Push 1 to the bottom of the stack
   2         Push 2 to stack
    ,%       Pop last 2 items, mod them and push result
      ?      If last item > 0
       +     Add the 1 to the input
        :    Else
         -   Subtract the 1 from the input

             No semicolon in code so print last item

```

# Braingolf v0.2, 9 bytes

```
.2%?1+:1-

```

Try it online! (Second argument is the Braingolf code, third argument is the input)

See above for explanation. Only difference is in Braingolf v0.2, the default behaviour of diadic operators, and the function of the `,` modifier, are reversed, meaning the 2 commas in the v0.1 answer are no longer needed.
> 7 votes

# Answer
## Python, 68 bytes

```
lambda x:[m.floor(x-m.cos(m.pi*x)) for m in [__import__('math')]][0]

```

In the spirit of a unique approach. The following graph shows the function (with purple dots representing the first 10 cases). It should in theory be possible to construct a solution for this question based on most (all?) periodic functions (e.g. sin, tan, sec). In fact, substituting cos for sec in the code as is should work.
> 7 votes

# Answer
# Cubix, ~~10~~ 9 bytes

```
cO1)I(//@

```

Try it online

### Explanation

Net version

```
    c O
    1 )
I ( / / @ . . .
. . . . . . . .
    . .
    . .

```

The executed characters are

```
I(1c)O@
I          Input
 (         Decrement
  1c       XOR with 1
    )      Increment
     O@    Output and exit

```
> 5 votes

# Answer
# APL (Dyalog Unicode), 6 bytes

-2 thanks to Razetime

```
⊢-¯1*⊢

```

Try it online!

Explanation:

```
 ⊢-¯1*⊢
   ¯1*⊢  ⍝ calculate ¯1*⍵ - for even ⍵: 1, for odd ⍵: ¯1.
 ⊢-      ⍝ subtract 1 for even, subtract ¯1 (add 1) for odd.

```
> 5 votes

# Answer
# JavaScript (ES6), ~~14~~ ~~13~~ ~~12~~ 10 bytes

```
n=>-(-n^1)

```
* 1 byte saved thanks to Luke.
* 2 bytes saved by porting feersum's C solution. (If that's frowned upon, please let me know and I'll roll back to my previous solution below)

---

## Try It

```
f=
n=>-(-n^1)
i.addEventListener("input",_=>o.innerText=f(+i.value))
```

```
<input id=i type=number><pre id=o>
```

---

## Original, 12 bytes

```
n=>n-1+n%2*2

```
> 4 votes

# Answer
# Javascript, 17 12 bytes

```
x=>x-(-1)**x

```

```
f=x=>x-(-1)**x;
```

```
<input id=i oninput=o.innerText=f(this.value) type=number><pre id=o>
```

# Another approach, 10 bytes stolen from the C answer (sssshhh)

```
x=>-(-x^1)

```

```
f=x=>-(-x^1)
```

```
<input id=i oninput=o.innerText=f(this.value) type=number><pre id=o>
```
> 3 votes

# Answer
# PHP, 15 bytes

```
<?=-(-$argn^1);

```
> 3 votes

# Answer
# Cubix, 11 bytes

```
u%2!I(/+@O<

```

Try it online!

# Explanation

Net version:

```
    u %
    2 !
I ( / + @ O < .
. . . . . . . .
    . .
    . .

```

Characters are executed in following order:

```
I(2%!+O@
I        # Take a number as input
 (       # Decrement it
  2%     # Take the parity of the decremented number
         # (0 if the input is odd, 1 if it's even)
    !    # If that number is zero:
     +   #   Add 2
      O  # Output the number
       @ # Terminate the program

```
> 3 votes

# Answer
# Brain-Flak, 36 bytes

```
(({})(())){({}[()]<([{}])>)}{}({}{})

```

Try it online!

I'm personally really happy with this answer because it is a lot shorter than what I would deem a traditional method of solving this problem.

## Explanation

The first bit of code

```
(({})(()))

```

converts the stack from just `n` to

```
n + 1
  1
  n

```

Then while the top of the stack is non zero, we decrement it and flip the sign of the number under it

```
{({}[()]<([{}])>)}

```

The we remove the zero and add the two remaining numbers

```
{}({}{})

```
> 3 votes

# Answer
# Vyxal `r`, 4 bytes

```
‹ue+

```

Try it Online!

Me and the boys porting risky be like

## Explained

```
‹ue+
‹    # input - 1
 u   # -1
  e  # ^^ ** ^
   + # ^ + input

```
> 3 votes

# Answer
# Python, 20 bytes

```
lambda n:n+(n%2or-1)

```

`n%2or-1` will return 1 if it's odd, but if it's even, `n%2` is "false" (0), so it instead returns -1. Then we simply add that to `n`.

### Previous solution, 23 bytes

```
lambda n:[n-1,n+1][n%2]

```

`n%2` calculates the remainder when `n` is divided by 2. If it's even, this returns 0, and element 0 in this list is `n-1`. If it's odd, this returns 1, and element 1 in this list is `n+1`.
> 2 votes

# Answer
# Mathematica, ~~22~~ 19 bytes

Saved 3 bytes thanks to Greg Martin!

```
#-1[-1][[#~Mod~2]]&

```

### Previous answer, 22 bytes

```
#+{-1,1}[[#~Mod~2+1]]&

```

### Explanation (for previous answer)

Mathematica has the nice feature that operations such as arithmetic automatically thread over lists.

In this case, we take `Mod[#,2]` which will return 0 or 1, but we need to add 1 because Mathematica lists are 1-indexed. If it's **even**, this comes out to 1, so `#-1` is returned. If it's **odd**, this comes out to 2, so `#+1` is returned.
> 2 votes

# Answer
# Retina, 21 bytes

```
.+
$*
^11(?=(11)*$)

```

Try it online! My first Retina answer with two trailing newlines! Explanation: The first two lines convert from decimal to unary. The third and fourth lines subtract two from even numbers. The last line converts back to decimal, but adds one too.
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
(1^(

```

Try it online!
> 2 votes

# Answer
# Wise, 8 bytes

```
-::^~-^-

```

Try it online!

## Explanation

If this were the other way around, (decrement if odd, increment if even), it would be quite easy to do this.

We would just flip the last bit.

```
::^~-^

```

The fix here is that we flip the last bit while negative. The negative numbers are 1 off from the negation of the numbers `~` so this creates an offset resolving the problem.

So we just take out program and wrap it in `-`.

```
-::^~-^-

```
> 2 votes

# Answer
# R, 17 bytes

```
(n=scan())-(-1)^n

```

where `n=scan()` takes the digit value.
> 2 votes

# Answer
# brainfuck (8-bit), 51 bytes

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

```

Try it online!

Requires a fixed 8-bit cell size.

Decided to do something entirely on my own.

Inspired by some meme ARM code I wrote to check if it is a multiple of 4 (screenshot)

Instead of modulo, negate+xor, or binary AND, I shift out all the bits but the lowest to determine if it is even or odd.

```
// Checks parity by shifting n << 7.
// Requires 8-bit cells
,             // [  n    0    0   0]
              // copy loop, shifting one once
[->>++>+<<<]  // [  0    0 n<<1   n]
              // n <<= 6
+++           // c = 3
[-            // loop 3 times, shifting twice
    >>[-<++>] // [  c n<<1    0   n]
     <[->++<] // [  c    0 n<<1   n]
<]            // end loop
              // if even:
              //   tape[2]==0
              // else:
              //   tape[2]==0x80
>>[           // if tape[2] != 0:
    >++<[-]   //   n += 2
]
>-            // n -= 1
.             // print n

```

Equivalent C:

```
uint8_t parity(uint8_t n)
{
    uint8_t is_odd = n << 7;
    if (is_odd != 0)
        n += 2;
    return n - 1;
}

```

The input is a byte from stdin, and the output is a byte printed to stdout. 0-255 only.

The demo uses ASCII arithmetic.

# boolfuck (joke), 3 bytes

```
,+;

```

Try it online!

**For a real Boolfuck solution, see here**

Operation works on 1-bit integers from stdin, prints to stdout. Obviously a joke.
> 2 votes

# Answer
# Factor, 15 bytes

```
[ -1 over ^ - ]

```

Try it online!

Uses `x-(-1)^x` method as in many other answers (specifically inspired by the APL one).

In Factor, it is usually better (code-golf-wise) to minimize the number of conditionals, then minimize the number of functions overall (especially when the answer can be found with arithmetic, where all the functions have short names). The top answer beats a different arithmetic answer `x+x%2*2-1` (23 bytes)

```
[ dup 2 mod 2 * + 1 - ]

```

Try it online!

and a conditional-based answer `x+(x.odd()?1:-1)` (21 bytes)

```
[ dup odd? 1 -1 ? + ]

```

Try it online!
> 2 votes

# Answer
# Risky, 4 bytes

```
?+0--2?

```

Try it online!

### Explanation

```
?        The input number
 +0      plus 0
   -     minus
    -    -1
     2   to the power of
      ?  the input number

```
> 2 votes

# Answer
# Java 8, ~~16~~ 10 bytes

```
n->-(-n^1)

```

# Java 7, ~~34~~ 28 bytes

```
int c(int n){return-(-n^1);}

```

Boring ports of *@feersum*'s amazing C answer.
Try it here.

---

Old answers:

**Java 8, 16 bytes**

```
n->n%2<1?n-1:n+1

```

**Java 7, 34 bytes**

```
int c(int n){return--n%2>0?n:n+2;}

```

**Explanation (of old Java 7 answer):**

Try it here.

The answer above is a shorter variant of `int c(int n){return n%2<1?n-1:n+1;}` by getting rid of the space.

```
int c(int n){     // Method with integer parameter and integer return-type
  return--n%2>0?  //  If n-1 mod-2 is 1:
    n             //   Return n-1
   :              //  Else:
    n+2;          //   Return n+1
}                 // End of method

```
> 1 votes

# Answer
# braingasm, 8 bytes

```
;o[++]-:

```

`;` reads a number, `o[++]` increments twice if the number is odd, `-`decrements once, `:` prints.

edit: changed to `p` to `o` to retrofit to a breaking change in the language.
> 1 votes

# Answer
## Befunge 93, 18 bytes

```
&:2%#v_1+.@
@.-1 <

```

I am not done golfing this yet (I hope).
> 1 votes

# Answer
# Python, 20 bytes

```
lambda n:n+(n&1)*2-1

```
> 1 votes

# Answer
# Japt, 6 bytes

```
n ^1 n

```

Try it online!
> 1 votes

# Answer
# AWK, 15 bytes

```
{$1+=$1%2*2-1}1

```

Try it online!

I could save 1 byte by using `(-1)^$1`, but then it would be pretty much the same as everyone else, and this is what I came up with before looking at other answers. :)
> 1 votes

# Answer
# Groovy, 17 bytes

```
print x%2?x+1:x-1

```

Just substitute x for desired number. Try it online here -\> https://tio.run/nexus/groovy and copy the code.
> 1 votes

# Answer
# Ruby, 12 bytes

```
->n{-(-n^1)}

```
> 1 votes

# Answer
# J-uby, 12 bytes

```
:-@|:^&1|:-@

```

## Explanation

```
:-@|            negate n
    :^&1|       XOR it with 1
         :-@    negate that

```

With a change I just pushed to GitHub (inspired by this question, but overall useful), it becomes 10 bytes:

```
:-|:^&1|:-

```
> 1 votes

# Answer
# Chip, 61 bytes

```
  * *
A~#-#a
B~#~#b
C~#~#c
D~#~#d
E~#~#e
F~#~#f
G~#~#g
H~#~#h

```

Try it online!

Since Chip natively handles only byte-sized integers, this solution reads in and writes out bytes. The TIO is set up to use the `\x00` notation for this.

This Chip solution uses a straightforward approach where the columns are the operations, and the rows are for each bit:

```
Read in an octet
|Invert all bits
||Increment
|||Invert all bits except the lowest bit
||||Increment
|||||Output the octet
||||||

  * *
A~#-#a
B~#~#b
C~#~#c
D~#~#d
E~#~#e
F~#~#f
G~#~#g
H~#~#h

```
> 1 votes

# Answer
# Klein, 21 + 3 bytes, (non-competing)

Uses the `000` topology.

```
:(1-(\))++@
1-+:?\)-(

```

## Explanation

The first bit executed is `:(1-(`. This puts a copy of the input and a `-1` in the scope to be recalled later. This is just required set up for future computation.

The two mirrors `\\` then move the ip down a level into the main loop. The main loop, unfolded, is:

```
)-(1-+:?\

```

This recalls the first number of the scope and flips its sign then decrements the tos. It will continue to flip the sign back and forth until it reaches zero. This way it will be `-1` if our input was even and `1` if it was odd. Once the counter has reached zero `?` stops jumping over the mirror and the pointer wraps around to the top. Now the mirror we used earlier deflects the ip to the right causing it to run the code `))++@`.

This code recalls the two things from the scope (the copy of the input and the number we have been flipping) with `))`. And adds the top three items with `++`. Since the counter is at zero the result is just the sum of the number we built and the input. Since it can be either `-1` or `1` depending on the parity of the input this will flip the sign of the input.

Finally `@` ends execution.
> 1 votes

# Answer
# Casio-Basic, 27 bytes

```
piecewise(mod(n,2),1,-1)+n

```

26 bytes for the function, +1 to enter `n` in the parameters box.
> 1 votes

# Answer
# Ly, 8 bytes

```
n:2%2*+,

```

Try it online!

Explanation:

```
n:2%2*+,

n        # take input
 :2%     # modulo two
    2*   # multiply by two
      +  # add to input
       , # decrement

```
> 1 votes

# Answer
# tinylisp, 38 bytes

```
(load library
(q((N)((i(odd? N)a s)N 1

```

Try it online! (Adds 4 bytes to bind the lambda function to a name for ease of testing.)

### Ungolfed

```
(load library)
(lambda (N)
  ((if (odd? N) add2 sub2) N 1))

```

Pretty straightforward implementation of the spec: if N is odd, add 1 to N; if not, subtract 1 from N. The main trick is that the if needs only swap out which function we're calling (addition vs. subtraction); the arguments (N and 1) are the same in either case.
> 1 votes

# Answer
# MAWP, 18 bytes

```
%@!!2P2WA{M:}<1A:>

```

Try it!
> 1 votes

# Answer
# Perl 5, 12 bytes

```
$_+=$_%2||-1

```

Try it online!
> 1 votes

# Answer
# x86-16 machine code, 5 bytes

Binary:

```
00000000: 4834 0140 c3                             H4.@.

```

Listing:

```
48      DEC  AX             ; decrement input (parity now inverted)
34 01   XOR  AL, 1          ; if LSb is 0 (odd input) add 1, otherwise subtract 1
40      INC  AX             ; increment
C3      RET                 ; return to caller

```

Callable function, input/output is `AL`.

Explanation:

Classic `XOR` shenanigans to accomplish this equivalent `if/else` pseudocode:

```
AL = AL - 1
if ( AL & 1 == 0 ) AL = AL + 1
else AL = AL - 1
AL = AL + 1

```

**Edit:**

Well heck:

Silly me for not looking at existing submissions before starting. This approach was suggested by Ilmari Karonen in 2017!
> 1 votes

# Answer
# Zsh, 14 bytes

```
<<<$[-(-$1^1)]

```

Try it online!
> 1 votes

# Answer
# Python 3, 18 bytes

```
lambda n:n+n%2*2-1

```

Try it online!

Explanation: Take the modulo of "n" and double it

Subtract that off the original "n" and subtract another 1

Basically, the same but easier to understand:

```
lambda n:n-(1-n%2*2)

```
> 1 votes

# Answer
# Boolfuck, ~~91~~ ~~57~~ 56 bytes

```
,>,>,>,>,>,>,>+<<<<<<<+[>+]<[<]>+[>]+<[+<]>;>;>;>;>;>;>;

```

Try it online!

**Yes, a real solution using Boolfuck.**

Works on 7-bit integers, reads and writes in raw semibytes.

There might still be some optimization room here.

I mostly wanted to avenge my `,+;` meme.

```
,>,>,>,>,>,>,       read 7 bits
>+<<<<<<<+[>+]<[<]> decrement
+                   xor 1
[>]+<[+<]           increment
>;>;>;>;>;>;>;      print

```
> 1 votes

# Answer
# Python 3, ~~36~~ 31 bytes

```
def f(n):return n+(-1)**(n%2+1)

```
> 1 votes

# Answer
# Jelly, 4 bytes

```
‘’Ḃ?

```

Try it online!
> 0 votes

# Answer
# C, 29 bytes

```
a(int b){return b%2?b+1:b-1;}

```
> 0 votes

# Answer
# C#, ~~34~~ 11 bytes

```
n=>-(-n^1);

```

Port of *@feersum*'s amazing C answer.
Try it here.
> 0 votes

# Answer
## Batch, 20 bytes

```
@cmd/cset/a"-(1^-%1)

```

Independently rediscovered @feersum's algorithm, honest!
> 0 votes

# Answer
# CJam, ~~7~~ 6 bytes

```
{(1^)}

```

Try it online!

*-1 thanks to Martin Ender. ......**.........OOOO***
> 0 votes

# Answer
# Swift, 29 bytes

```
var f={(i)->Int in i-1+i%2*2}

```

Try it here
> 0 votes

# Answer
# Fourier, 17 bytes

```
I~x^ox%2{0}{@xvo}

```

**Try it on FourIDE!**

Explanation:

```
I~x                 - Stores input in a variable called x
   x^o              - Increments x and outputs
      x%2{0}{    }  - If x mod 2 == 0, do code inside brackets
             @      - Clear screen
              xvo   - Decrements x and outputs

```
> 0 votes

# Answer
## QBIC, ~~15~~ 10 bytes

```
:?a-(-1)^a

```

Saved a lot by using a different calculation.

Explanation:

```
:           Get a number frm the cmd line as var a
?           PRINT
 a-(-1)^a   a decreased by 1 for when even, or -1 (adding one) when odd.

```

QBasic (and QBIC) need the parenteses around `(-1)`, because code like `-1^2` is otherwise seen as `negate 1*1 = negate 1 = -1`...
> 0 votes

# Answer
# 05AB1E, 7 bytes

```
D1(sm-Ä

```

Try it online!

Explanation:

```
D1(sm-Ä
               Input (implicit). Is 3 for example. Stack: [3]
D              Duplicate input. Stack: [3, 3]
  1            Push 1. Stack: [3, 3, 1]
    (          Push opposite of top of stack. Stack: [3, 3, -1]
      s        Swap the top 2 items on the stack. Stack: [3, -1, 3]
        m      Push -1**3. Stack: [3, -1]
           -   Subtract. Stack: [4].
            Ä  Absolute value. Stack: [4].
               Implicit output.

```
> 0 votes

# Answer
## Excel, 11 bytes

```
=A1-(-1)^A1

```

Assumes input in `A1`.
> 0 votes

# Answer
## SAS, 72 bytes

```
%macro t(n);%put%eval(&n+%sysfunc(ifn(%sysfunc(mod(&n,2)),1,-1)));%mend;

```
> 0 votes

# Answer
# dc, 10

```
?d2%2*+1-p

```

Uses the same formula as @TuukkaX's python answer.

Try it online.
> 0 votes

# Answer
## Pyth, 4 bytes

I'm new to Pyth, so please tell me if there are any things I can golf.

```
_x1_

```

Explanation:

```
   _    Negate input
 x1     Bitwise XOR with 1
_       Negate

```
> 0 votes

# Answer
## Excel VBA 27 bytes

```
[a2]=iif(n mod 2=0,n-1,n+1)

```
> 0 votes

# Answer
## Pyth, 10 bytes

```
+Q?%Q2 1_1

```

Try it online

As simple as using modulo of input with 2 and the ternary operator.
> 0 votes

# Answer
# Actually, 6 bytes

```
;0Dⁿ@-

```

Try it online, or run all test cases at once!

Explanation:

```
;0Dⁿ@-
;0Dⁿ    (-1)**n
    @-  n - (above)

```
> 0 votes

# Answer
# Tcl, 30

```
proc s n {expr $n%2?$n+1:$n-1}

```

demo
> 0 votes

# Answer
# Tcl, 24

based on @feersum's answer

```
 proc s n {expr -(-$n^1)}

```

demo

---

# Tcl, 23

If it is a program instead of a function I can shave one byte off.

```
puts [expr -(-$argv^1)]

```

demo
> 0 votes

# Answer
# Befunge-93, 11 bytes

```
&:2%2*1-+.@

```

\[Try it online!\]

### Explanation:

Stack representation: `bottom [A, B, C top`

```
&:             Pushes 2 copies of the input, N:                   [N, N
  2%           Mods the top copy by 2, so it's either 1 or 0:     [N, (N % 2)
    2*         Multiplies that by 2, so that it's either 2 or 0:  [N, ((N % 2) * 2)
      1-       Subtracts 1, so it's either 1 or -1:               [N, (((N % 2) * 2) - 1)
        +      Adds the 2 together. -1 for evens, and 1 for odds: [(N-1) or [(N+1)
         .@    Prints and ends

```

### Befunge-98 Variant, 10 bytes

This program can be trivially modified for Befunge-98 by removing the `@`, meaning the program will wrap around to the `&` and end:

```
&:2%2*1-+.

```

Try it online!
> 0 votes

# Answer
# x86 machine code, 8 bytes

Load register `al` with an 8 bit integer

```
A8 01 (test al, 1; and whatever is in al with one, fast and small method for checking odd/even)
74 04 (jz 8; jump to even code if zf (zero flag, will be set if above instruction returns 0) is set)
04 02 (add al, 2; Two, because the next instruction will subtract one again, as if I incremented and jumped past the dec but shorter and faster)
FE C8 (dec al; Explained above, this is the code that is jumped to if input is even)

```

If you want, here is some actual assembly in boot-sector format. Just assemble this with `nasm filename.asm` and run `qemu-system-i386 filename` to test it. Press a key, and you will see that it will be the next letter if the ascii code was odd, or previous if it was even.

```
[ORG 0x7C00]

start:
xor ah, ah ;bios keyboard: get character (xoring a register with itself is a fast way to set it to 0 which is what we need)
int 0x16 ; keyboard io bios interrupt
mov ah, 0x0e ;bios graphics: display character (get ready)

test al, 0x01
jz even

add al, 2
even:
dec al
int 0x10 ; we already set al to 0E: display character, which takes a character from al and outputs that.

jmp start ; just go back to the start and get another character

times 510-($-$$) db 0 ; bootsector padding/signature
db 0x55
db 0xAA

```

Almost forgot, I should probably add the original assembly code that I used to create the bytes above

```
test al, 0x01
jz even

;odd code
add al, 2
even:
dec al

```
> 0 votes

# Answer
## Clojure, 21 bytes

```
#(+(if(odd? %)1 -1)%)

```

It is quite difficult to get creative with this.
> 0 votes

# Answer
@REXX 35 Bytes

```
arg a
x=pos(".",a/2)-1
say a+abs(x)/x

```

Explanation: Explanation: There is no distinction in Rexx between numbers and strings. The action you perform is what defines the type. The "typing" applies just to that action and can change at any time.

So, after dividing the number by 2 we then search for the decimal point. Subtract 1 from its position giving -1 if it was not found and a value in the range 1-n if it was. (Note that 1/2 returns 0.5 and not .5 so pos can never be 1 and therefore x can never be 0).

Try it here

REXX functions and instructions
> 0 votes

# Answer
# ,,,, 4 bytes

```
_1^_

```

Yay.

## Explanation

```
_1^_

      input by command-line args
_     negate
 1    push 1
  ^   pop input and 1 and push input ^ 1 (bitwise XOR)
   _  negate
      implicit output

```
> 0 votes

# Answer
**Haskell, 21 bytes**

```
f x|odd x=x+1|0<1=x-1

```

I have no idea why I'm doing this xD
> 0 votes

# Answer
# Common Lisp, 24 bytes

```
(lambda(x)(- x(expt -1 x)))

```

Try it online!
> 0 votes

# Answer
# J, 9 bytes

```
(22 b.)&1

```

`22 b.` is XOR. Port of Cyoce's ruby answer.

Try it online!

### Alternative straightforward answer:

+1:\`\_1:@.(2&|)

Try it online!
> 0 votes

# Answer
# Keg, `-hr`, 7 bytes

```
:2%[;|⑨

```

Try it online!
> 0 votes

# Answer
# Japt, 4 bytes

```
aJpU

```

Try it (includes all test cases)

```
aJpU     :Implicit input of integer U
a        :Absolute difference with
 J       :  -1
  pU     :  Raised to the power of U

```
> 0 votes

# Answer
# Lua (40 bytes)

Using a table in order to avoid `math.ceil` or `math.floor`

```
function m(n)return n+({-1,1})[1+n%2]end

```
> 0 votes

# Answer
# BRASCA, 7 bytes

```
ig{1_}n

```

Try it online!

## Explanation

```
i       - Turn ASCII codepoints 48-57 to numbers 0-9
 g      - Concatenate stack
  {     - Decrement
   1_   - XOR by 1
     }  - Increment
      n - Output as number

```
> 0 votes

# Answer
# TI-Basic, 7 bytes

```
Ans-i^(2Ans

```

Takes input in `Ans`. Output is stored in `Ans` and is displayed.

---

Alternatively, 9 bytes:

```
Ans-cos(2πfPart(Ans/2

```
> 0 votes

# Answer
# \>\<\> (Fish), 10 bytes

```
:2%2*+1-n;

```

Try it
> 0 votes

# Answer
# Thunno 2, 5 bytes

```
Ṅ1Æ^Ṅ

```

Attempt This Online!

#### Explanation

```
Ṅ1Æ^Ṅ  # Implicit input
    Ṅ  # -(        )
Ṅ      #   -input
  Æ^   #         ^
 1     #          1
       # Implicit output

```
> 0 votes

---
Tags: code-golf, number
---


title: Sum the numbers on standard in

text:
# Question
Title: Sum the numbers on standard in
Consider a stream/file with one integer per line. For example:

```
123
5
99

```

Your code should output the sum of these numbers, that is `227`.

The input format is strictly one integer per line. You cannot, for example, assume the input is on one line as an array of integers.

You can take input either from STDIN, in form of a filename, or a file with a name of your choice; you can choose which one. No other ways of getting input are allowed.

The input will contain at least one integer. You can assume all integers are non-negative and that their total sum is less than `2<sup>32</sup>`.

# Answer
# 05AB1E, 2 bytes

```
|O

```

Explanation:

```
|   Get input as array
 O  Sum

```

Try it online!
> 16 votes

# Answer
## Bash + coreutils, 16 bytes

```
xargs|tr \  +|bc

```

**Try it online!**

There are two spaces after the `\`. This works for negative numbers as well.

**Explanation:**

```
xargs             # known trick to turn newlines into spaces, while adding a
                  #trailing newline when printing the result (needed for bc)
|tr \  +          # turn spaces into '+'s
|bc               # calculates the sum

```

You may wonder why `tr \\n +|bc` isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors:

* if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition
* and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s.
> 22 votes

# Answer
# MATL, 2 bytes

```
Us

```

This expects the input in a text file called `defin`.

*Gif or it didn't happen*:

Or **try it online!** (*thanks to Dennis for the set-up!*)

### Explanation

When a MATL program is run, if a file called `defin` is found (the name refers to "default input"), its contents are automatically loaded as text and pushed to the stack as a string before executing the code.

Function `U` evaluates the string to convert it to a column vector of numbers, and `s` computes the sum, which is implicitly displayed.
> 14 votes

# Answer
# Japt, 2 bytes

```
Nx

```

### Explanation

```
     Implicit: parse STDIN into array of numbers, strings, and arrays
N    Get the resulting parsed array.
 x   Sum.
     Implicit: output result of last expression

```

Try it online!
> 13 votes

# Answer
# Perl 6, 13 bytes

```
say sum lines

```

Try it

## Explanation

* `lines()` returns a list of lines from `$*IN` or `$*ARGFILES` a “magic” command-line input handle.
* `sum(…)` was added to Perl 6 to allow `[+] List` to be optimized for Positionals that can calculate their sum without generating all of their values like `1..100000`
(I just thought `sum` was just too cute here to use `[+]` like I normally would)
* `say(…)` call the `.gist` method on its input, and prints it with an additional newline.
> 12 votes

# Answer
# Paste + bc, 13 bytes

```
paste -sd+|bc

```

Explanation:

```
paste -s        Take one line at a time from input
        d+      Joining by '+'
          |bc   Pass as expression to bc

```

Another shell answer!
> 12 votes

# Answer
# C, 53 bytes

```
r;main(i){for(;~scanf("%d",&i);r+=i);printf("%d",r);}

```
> 10 votes

# Answer
# Python 3, 28 bytes

```
print(sum(map(int,open(0))))

```

Taken from this tip. I've been told this won't work on Windows.

Try it online!
> 9 votes

# Answer
# Retina, ~~11~~ 7 bytes

-4 thanks to Martin Ender

```
.*
$*
1

```

Try it online!

---

Convert to unary:

```
.*
$*

```

Count the number of `1`s:

```
1

```
> 9 votes

# Answer
# Brain-Flak, 20 bytes

```
(([]){[{}]{}([])}{})

```

Try it online!

## Explanation

This is a golf off of a solution made by Riley in chat. His solution was:

```
([])({<{}>{}<([])>}{})

```

If your familiar with Brain-Flak this is pretty self-explanatory. It pushes the stack height and pops one value as it counts down, at the end it pushes the sum of all the runs.

It is a pretty good golf but he zeros both `{}` and `([])` however these will have a values that only differ by one so if instead we remove the masks and make one of the two negative they should nearly cancel out.

```
([])({[{}]{}([])}{})

```

Since they always differ by one we have the unfortunate circumstance where our answer is always off by the stack height. In order to remedy this we simply move the beginning of the push to encompass the first stack height.

```
(([]){[{}]{}([])}{})

```
> 8 votes

# Answer
# Python 2, 40 bytes

```
import sys;print sum(map(int,sys.stdin))

```
> 8 votes

# Answer
# Perl 5, 9 bytes

8 bytes of code + `-p` flag.

```
$\+=$_}{

```

Try it online!

With `-p`, the input is read one line at a time, stored in `$_` each time. We use `$\` as accumulator, because thanks to `-p` flag, it's implicitly printed at the end. The unmatched `}{` are used so `-p` flag only prints `$\` once at the end instead of printing `$_` and `$\` at each line it reads like it normally does.
> 8 votes

# Answer
# Pure Bash, ~~37~~ 36 bytes

*Thanks to @KevinCruijssen for a byte!*

```
while read a;do((b+=a));done;echo $b

```

Try it online!
> 7 votes

# Answer
## R,11 bytes

```
sum(scan())

```

`scan` takes the input, one number per line. And `sum`, well, sums.
> 7 votes

# Answer
## Haskell, 32 bytes

```
interact$show.sum.map read.lines

```

Try it online!.

`interact` collects the whole input from stdin, passes it to the function given as its argument and prints the string it gets back from this function. The function is:

```
            lines   -- split input into list of lines at nl
      map read      -- convert every line to a number (read is polymorphic,
                    -- but as want to sum it later, the type checker knows
                    -- it has to be numbers)
    sum             -- sum the list of numbers
show                -- convert back to string

```
> 6 votes

# Answer
# PHP, 22 bytes

```
<?=array_sum(file(t));

```

This assumes there is a file named "t" with a list of integers.

`file()` opens a file and returns an array with each line stored a separate element in the array. `array_sum()` sums all the elements in an array.
> 6 votes

# Answer
# Awk, 19 bytes

```
{s+=$1}END{print s}

```

Explanation:

```
{s+=$1}                For all lines in the input, add to s
        END             End loop
           {print s}    Print s

```
> 5 votes

# Answer
# dc, 14 bytes

```
0[+?z2=a]dsaxp

```

Try it online!

Explanation:

```
 [      ] sa   # recursive macro stored in register a, does the following:
  +            # - sum both numbers on stack
               #   (prints to stderr 1st time since there's only 1)
   ?           # - read next line, push to stack as number
    z          # - push size of stack
     2         # - push 2
      =a       # - if stack size = 2, ? yielded something, so recurse
               # - otherwise end macro (implicit)
0              # push 0 (accumulator)
         d     # duplicate macro before storing it
            x  # Call macro
             p # The sum should be on the stack now, so print it

```
> 5 votes

# Answer
# Python, ~~38~~ 30 bytes

```
lambda n:sum(map(int,open(n)))

```

In python, files are opened by `open('filename')` (obviously). They are, however, iterables. Each time you iterate through the file, you get the next line. So map iterates over each list, calling `int` on it, and then sums the resulting list.

Call with the filename as input. (i.e. `f('numbers.txt')`)

8 bytes saved by using `map(int, open(n))` instead of a list comprehension. Original code:

```
lambda n:sum([int(i)for i in open(n)])

```
> 4 votes

# Answer
# CJam, 5 bytes

```
q~]1b

```

Try it online!

### How it works

```
q     e# Read all input from STDIN.
 ~    e# Evaluate that input, pushing several integers.
  ]   e# Wrap the entire stack in an array.
   1b e# Convert from base 1 to integer.
      e# :+ (reduce by sum) would work as well, but 1b handles empty arrays.

```
> 4 votes

# Answer
## Mathematica, 19 bytes

Assumes Mathematica's notebook environment.

```
Tr[#&@@@Import@"a"]

```

Expects the input to be in a file `a`.
> 4 votes

# Answer
# Jelly, ~~9~~ 8 bytes

```
ƈFÐ¿FỴVS

```

STDIN isn't really Jelly's thing...

Try it online!

### How it works

```
ƈFÐ¿FỴVS  Main link. No arguments. Implicit argument: 0

  Ð¿      While loop; while the condition returns a truthy value, execute the body
          and set the return value to the result. Collect all results (including 0,
          the initial return value) in an array and return that array.
ƈ           Body: Yield a character from STDIN or [] if the input is exhausted.
 F          Condition: Flatten, mapping 0 to [], '0' to "0", and [] to [] (falsy).
    F     Flatten the result.
     Ỵ    Split at newlines.
      V   Evaluate the resulting strings.
       S  Take the sum.

```
> 4 votes

# Answer
# Brachylog, 4 bytes

```
ṇịᵐ+

```

Try it online!

### Explanation

```
ṇ         Split the Input on linebreaks
 ịᵐ       Map: String to Integer
   +      Sum

```
> 4 votes

# Answer
# Pure bash, 30

```
read -d_ b
echo $[${b//'
'/+}]

```

Try it online.

* `read`s the input file in one go into the variable `b`. `-d_` tells `read` that the line delimiter is `_` instead of `newline`
* `${b//'``newline``'/+}` replaces the newlines in `b` with `+`
* `echo $[ ... ]` arithmetically evaluates the resulting expression and outputs it.
> 4 votes

# Answer
# Vim, 16 bytes/keystrokes

```
:%s/\n/+
C<C-r>=<C-r>"<C-h>

```

Since V is backwards compatible, you can Try it online!
> 3 votes

# Answer
# Pyth, 3 bytes

```
s.Q

```

Try it online!

```
 .Q  Read all of standard input, evaluating each line.
s    Take the sum.

```
> 3 votes

# Answer
# jq, 5 bytes

`add`, plus the command line flag `-s`.

For example:

```
% echo "1\n2\n3\n4\n5" | jq -s add
15

```
> 3 votes

# Answer
# Ruby, ~~19~~ 15 bytes

Loving that new `#sum` in Ruby 2.4 :)

```
p$<.sum(&:to_i)

```

This program accepts input from either stdin or any filename(s) given as command line argument
> 3 votes

# Answer
# Actually, 2 bytes

Try it online!

Explanation:

```
kΣ
    (implicit input - read each line, evaluate it, and push it to the stack)
k   pop all stack elements and push them as a list
 Σ  sum
    (implicit output)

```
> 3 votes

# Answer
# dc, 22

```
[pq]sq0[?z2>q+lmx]dsmx

```

This seems rather longer than it should be, but it is tricky to decide when the end of the file is reached. The only way I can think of to do this is check the stack length after the `?` command.

Try it online.

```
[pq]                    # macro to `p`rint top-of-stack, then `q`uit the program
    sq                  # save the above macro in the `q` register
      0                 # push `0` to the stack.  Each input number is added to this (stack accumulator)
       [         ]      # macro to:
        ?               # - read line of input
         z              # - push stack length to stack
          2             # - push 2 to the stack
           >q           # - if 2 > stack length then invoke macro stored in `q` register
             +          # - add input to stack accumulator
              lmx       # - load macro stored in `m` register and execute it
                  d     # duplicate macro
                   sm   # store in register `m`
                     x  # execute macro

```

Note the macro `m` is called recursively. Modern `dc` implements tail recursion for this sort of thing, so there should be no worries about overflowing the stack.
> 3 votes

# Answer
# Python 2, ~~50~~ ~~45~~ 43 bytes

Pretty self-explanatory.

```
s=0
try:
    while 1:s+=input()
except:print s

```

**Try it online**
> 2 votes

# Answer
# Pyke, 4 bytes

```
zbrs

```

Try it online!

```
z    -   input()
 b   -  int(^)
  r  - if no errors: goto start
   s - sum(stack)

```
> 2 votes

# Answer
# GS2, 2 bytes

```
Wd

```

Try it online!

### How it works

```
    (implicit) Read all input from STDIN an push it as a string.
W   Extract all integers, pushing a single array.
    For input x, this executes map(int, re.findall(r'-?\d+', x)) internally.
 d  Take the sum.

```
> 2 votes

# Answer
## GNU sed \+ bc, 34 bytes

```
:
$!N
$!b
y:\n:+:
s:.*:echo &|bc:e

```

**Try it online!**

It is possible to do a shell call from inside sed, and as such I use bc to calculate the sum. Lines 1 to 4 only prepare the input necessary for that calculation. This works for negative numbers as well.

**Explanation:**

```
:                    # start reading loop
$!N                  # if not EOF, read and append a new input line to pattern
$!b                  # repeat
y:\n:+:              # turn all newlines into pluses
s:.*:echo &|bc:e     # shell call to bc with pattern as input (calculates sum)
                     # implicit printing

```

**Pure GNU sed program: 236 + 1(r flag) = 237 bytes** (as promised some time ago)

There are no data types or any math operations in sed. I have tried various methods, but it turns out that concatenating the numbers in unary format and converting the result back to decimal is the simplest way. This works for non-negative integers only, compared to the code above, however this is precisely what the challenge stated in the first place.

```
G;s:\n::
# concatenate current decimal number with the intermediary unary sum, if any
h;:;s:\w::2g;y:9876543210:87654321\t :;/ /!s:;|$:@:;/\s/!t;x;s:.::;x;G;s:;.*::m;s:\s::g;/\w/{s:@:&&&&&&&&&&:g;t}
# convert the decimal number to unary (using '@' as digit)
y:@:;:
# change unary digit from '@' to ';', to not interfere with above on the next cycle
h;$!d
# store intermediary unary sum and start next reading cycle if input lines left
s:^:0:;/;/{:d;s:^9+:0&:;s:.9*;:/&:;h;s:.*/::;y:0123456789:1234567890:;x;s:/.*::;G;s:\n::;s:;::;/;/td}
# convert final unary sum to decimal (result), plus implicit printing at the end

```

**Try it online!**

The program does bignum arithmetic, as long as sed can store in memory the unary result.
> 2 votes

# Answer
# Powershell, 18 Bytes

```
(gc 1)-join"+"|iex

```

this assumes the file is named '1' with no extension.

alternate 24 byte version, takes filename as input:

```
(gc "$args")-join"+"|iex

```

explanation:

`(` `g`et `c`ontent of the file `"$args"` `)` then `-join` the lines together with a `"+"` to form a valid-syntax sum, then `|` `i`nvoke `ex`pression to calculate it as if it was typed into the console directly.

if output is allowed in the following format:

```
Count    : 3
Average  :
Sum      : 227
Maximum  :
Minimum  :
Property :

```

then `gc 1|measure -s` is a valid 15 byte solution, thanks to @AdmBorkBork for pointing that out.
> 2 votes

# Answer
## Batch, 55 bytes

```
@set s=0
@for /f %%n in (%1)do @set/as+=%%n
@echo %s%

```

Takes the file to be summed as a command-line parameter.
> 2 votes

# Answer
## MATLAB: 17 bytes

```
sum(dlmread('x'))

```

Assumes a file named 'x' in current directory. `dlmread` reads numeric values from a file using delimiters - if no delimiter is specified as the second argument, it will infer from the file type. It successfully infers `\n` as the delimiter in a file as specified by the question, then uses `sum` to add them up.
> 2 votes

# Answer
## QBasic 4.5, ~~61~~ 59 bytes

Since QBasic isn't the greatest with streams, the input is assumed in a file called "a".

*Minus 2 bytes because @DLosc showed me an alternate syntax for one of QBasic's most iconic commands. Does QBasic really hold no secrets for you?*

```
OPEN"I",1,"a"
WHILE EOF(1)=0:INPUT#1,b$:x=x+VAL(b$)
WEND:?x

```
> 2 votes

# Answer
# C#, 121 bytes

Java, but no C#? That will not do...

```
using C=System.Console;class P{static void Main(){int a=0,b;for(;int.TryParse(C.ReadLine(),out b);)a+=b;C.WriteLine(a);}}

```

Try it Online

Since this score is worse than Java's, we'd better provide a 95 byte context-less function also:

```
using C=System.Console;int S(){int a=0,b;for(;int.TryParse(C.ReadLine(),out b);)a+=b;return a;}

```

Formatted and commented:

```
using C=System.Console;

class P
{
    static void Main()
    {
        int a=0,b; // a is accumulator, b is tempory storage
        for(;int.TryParse(C.ReadLine(),out b);) // read a line, try to parse it as an integer (expects a trailing new-line)
            a+=b; // add to accumulator
        C.WriteLine(a); // print accumulator
    }
}

```

I was really hoping to have some code like the following:

```
int a=0,b=0,c;
for(;(c=C.Read())>0;)
    b=c<15?(a+=b)*0:b*10+c-48;
C.WriteLine(a);

```

But it just doesn't pay :(

Just for fun, the `try...catch` solution is also 121 bytes

```
using C=System.Console;class P{static void Main(){int a=0;try{for(;;)a+=int.Parse(C.ReadLine());}catch{}C.WriteLine(a);}}

```
> 2 votes

# Answer
# Pip, 4 bytes

3 bytes of code, +1 for `-r` flag.

```
$+g

```

Try it online!

`$+g` is the standard "sum all inputs" program--read it as `fold-plus(arglist)`. Normally the arglist is taken from command-line arguments. The `-r` flag takes it from lines of stdin instead.
> 2 votes

# Answer
# PostScript, 11

Consists of two files. File A: (2 bytes)

```
0[

```

File B: (8 bytes tokenized)

```
]{add}forall =

```

Invoke as: (1 byte for extra file)

```
$ gs a inputfile b

```

This takes advantage of the fact that the input format is also valid PostScript code that just pushes all the numbers on the stack.

This allows it to very cheaply create an array from them over which it can iterate, by using multiple files to place an initial value for the summation and the opening brace on the stack before the input file.
> 2 votes

# Answer
# Go, 146 bytes

```
package main
import("bufio";"os";"strconv")
func main(){
s:=bufio.NewScanner(os.Stdin)
n:=0
for s.Scan(){m,_:=strconv.Atoi(s.Text())
n+=m
print(n)}}

```
> 2 votes

# Answer
# Cubix, 15 bytes

I have two versions to do this. The first (and longest) is to specification. This will work with non negative integers only. A negative integer will be treated as a end of input, but zeros will be handled correctly.

```
O<u;Ii?;+...@._

```

Try it here
Expanded onto the cube

```
    O <
    u ;
I i ? ; + . . .
@ . _ . . . . .
    . .
    . .

```

This essentially reads in an integer and the seperator. If the separator is negative (EOF or negative) redirect up into a path that will remove two items from the stack, output the already summed results, grab a superfluous input and exit. Otherwise if the input is non negative remove from the stack then sum. This creates a rolling total.

The shorter (8 byte) non-compliant version will handle non-zero integers, but it treats 0 on the stack as the end of input.

```
@O;UI!W+

```

Try it here

```
    @ O
    ; U
I ! W + . . . .
. . . . . . . .
    . .
    . .

```
> 2 votes

# Answer
# Tcl, 33 bytes

```
puts [expr [join [read stdin] +]]

```

Try it online!
> 2 votes

# Answer
# Java 7, 109 Bytes

```
import java.util.*;int x;int s(){Scanner a=new
Scanner(System.in);while(a.hasNext())x+=a.nextInt();return x;}

```

Try it!

Reads from System.in
> 2 votes

# Answer
# QBIC, 19 bytes

```
{_?~A=Z|_Xp\p=p+!A!

```

## Explanation

```
{        DO infinitely
_?       Ask for user input, save as A$
~A=Z     IF input was nothing (Z$ = "")
|_Xp     THEN QUIT, printing the total
\p=p+    ELSE increase the total by
     A   the given input
    ! !  cast as a number

```
> 2 votes

# Answer
# T-SQL, ~~60~~ 59 bytes

```
SELECT 0a INTO n;BULK INSERT n FROM'd:n'SELECT SUM(a)FROM n

```

This is the kind of thing that SQL was designed to do, surprised there isn't already an answer for it. Tested on MS SQL 2012.

`SELECT 0a INTO n;` is slightly shorter than `CREATE TABLE n(a INT)`. Adding a zero row doesn't change the total.

Text file named `n` (no extension) is located in the current folder on the D: drive. `BULK INSERT` is shorter and easier than other file import options like `SELECT FROM OPENROWSET(BULK)` or `EXEC xp_cmdshell 'bcp.exe'`.

Of course if *input is allowed via a pre-existing table*, per our normal I/O standards, then this would be trivial (**19 bytes**):

```
SELECT SUM(a)FROM n

```

But of course this challenge is all about the IO...
> 2 votes

# Answer
# Implicit, ~~4~~ 3 bytes

```
©1Þ

```

I'm going to add a builtin for `©1` eventually (e.g. when I'm done working on bitwise). (Just kidding, I'm never going to get around to it.)

Explanation:

```
©1Þ
©1   consume all input as integers
  Þ  sum the entire stack

```

Try it online!
> 2 votes

# Answer
## Labyrinth, 8 bytes

```
?+
;,;!@

```

Try it online!

The left-most 2x2 block is the main loop:

```
?   Read integer.
+   Add to running total (initially zero).
,   Read character. 10 as long as there is another input, -1 at EOF which will
    exit the loop.
;   Discard the 10.

```

Once we hit EOF, the IP moves east from the `,`.

```
;   Discard the -1.
!   Output the sum.
@   Terminate the program.

```
> 1 votes

# Answer
# Java 7, 111 bytes

```
import java.util.*;int c(){Scanner c=new Scanner(System.in);int r=0;for(;c.hasNext();r+=c.nextInt());return r;}

```

Takes the input from STDIN.

Try it here.
> 1 votes

# Answer
# JavaScript (Node.js), 124 bytes

```
t=0;
r=require('readline').createInterface({input:process.stdin});
r.on('line',l=>{t-=-l});
r.on('close',()=>console.log(t))

```

Try it online!
> 1 votes

# Answer
# Julia, 44 bytes

```
print(sum(map(s->parse(Int,s),readlines())))

```
> 1 votes

# Answer
## Jellyfish, 24 bytes

```
p
/
+
j, ,']
1'[J-1
   0

```

Try it online!

### Explanation

Reading input isn't very flexible in Jellyfish. In particular, there's no easy way to read a variable number of integers from STDIN, except as a list literal. So the majority of this code is input.

The shortest way I've found is to read all of STDIN as a string, then wrap it in `[...]` and then evaluate the string. Thankfully, Jelly's parser only looks for whitespace as a separator in lists, not specifically for space characters. So the linefeed separation required by the challenge works.

So let's build up the code from the bottom:

```
   J-1
   0

```

Read all input.

```
   ,']
   J-1
   0

```

Append `]`.

```
 , ,']
 '[J-1
   0

```

Prepend `[`.

```
j, ,']
1'[J-1
   0

```

Evaluate.

```
/
+
j, ,']
1'[J-1
   0

```

Fold addition (in other words, sum).

```
p
/
+
j, ,']
1'[J-1
   0

```

Print the result.
> 1 votes

# Answer
## C++, 99 Bytes

```
using namespace std;int main(){string a;int b=0;while(1){getline(cin,a);cout<<(b+=stoi(a))<<"\n";}}

```

Not my finest work, and there's probably a far better way to go about doing this. Still, I figured that using a string was the optimal way of doing things, seeing as I felt conversions with 'cin' would take up a vast majority of my code otherwise.

Enjoy!
> 1 votes

# Answer
# Scala, 48 bytes

```
print(io.Source.stdin.getLines.map(_.toInt).sum)

```
> 1 votes

# Answer
# JavaScript (Node.js), 112 bytes

Improvements upon the other JavaScript answer and comment below it.

```
a=0
require('readline').createInterface({input:process.stdin}).on('line',l=>a+=+l).on('close',_=>console.log(a))

```

Try it online!

Given the split module (`npm install split`), it's much shorter:

# JavaScript (Node.js) with split module, 90 bytes

```
a=0
process.stdin.pipe(require('split')()).on('data',l=>a+=+l).on('end',_=>console.log(a))

```
> 1 votes

# Answer
## REXX, 47 bytes

```
s=0
pull n
do until n=''
  s=s+n
  pull n
  end
say s

```
> 1 votes

# Answer
## Alice, 11 bytes

```
/o
\i@/Hd&+

```

Try it online!

This feels a bit suboptimal with all those mirrors (and also because the `H` could also be a `+`, possibly allowing reuse there), but so far I've only found a handful of different 11-byte solutions.

### Explanation

```
/o
\i@/...

```

While it's sometimes possible to shorten it, this seems to be a good pattern for programs which a) one or more integers as input, b) transform them with a linear program in Cardinal mode (i.e. integer processing mode), c) want to output one integer. The instruction pointer (IP) first moves from `/` to `/` bouncing through the `i` which reads all input. Then the `...` is executed and the IP wrap around to the wrong. The `\` puts the IP again in Ordinal mode where `o` prints the integer as a decimal string and `@` terminates the program. So that's the framework I'm using here.

The core of the program is then just four commands:

```
H   Compute the absolute value of the top of the stack. The reason we're doing this
    is that the stack still holds the entire input as a string. But as soon as you
    try to pop a value in Cardinal mode, that string gets implicitly converted
    to the integers it contains. So in this case, the H itself doesn't really
    do anything but it forces the input to be converted. We could also use
    + here and already sum the top two values (if there's only one value it
    would get added to an implicit zero, so that's fine).
d   Push the stack depth, i.e. the number of integers in the input.
&   Execute the next command that many times.
+   Add the top two numbers of the stack. Of course this is one more addition
    than we need, but there are only implicit zeros beneath the input so
    they don't change the result.

```
> 1 votes

# Answer
# Triangular, 15 bytes

```
(\$]U]P.%p/+U(<

```

Try it online!

Formats into this triangle:

```
    (
   \ $
  ] U ]
 P . % p
/ + U ( <

```

Explanation:

The IP starts from the top of the triangle, moving Southeast. So the first code that is executed is this:

```
($]

```

That simply reads integers as input until there is no more input.

This is how the interpreter sees the next part:

```
p(U+P]U%

```
* `p` pops the EOF from the stack.
* `(` opens a loop (to add the inputted integers).
* `U` pulls the "memory" (register) value onto the stack if it is not zero.
* `+` adds the top two stack values together, pops them, and pushes the result.
* `P` pops the top of stack into memory. Now, if we've added all inputted integers together, nothing will be on the stack.
* `]` ends the loop if the top of the stack is falsy (or the stack is empty).
* `U` pulls the memory value onto the stack.
* `%` prints it.
* Another loop is created at the end of the code, but that doesn't do anything as the IP runs off the playing field and terminates.
> 1 votes

# Answer
# JavaScript (Node.js), 78 bytes

```
process.stdin.on("data",r=>console.log((""+r).split`
`.reduce((a,v)=>+a+ +v)))

```

No `require`s needed for this one, just native NodeJS.

Try it online!
> 1 votes

# Answer
## Dart, 96 bytes (non async), 132 bytes (async)

Non async:

```
import'dart:io';main(){_ s;_ i=0;while((s=stdin.readLineSync())!=null)i+=int.parse(s);print(i);}

```

Dart allows you to define local variables with types that don't exist when running in uncheck mode (which is the default mode). This program doesn't function in checked mode.

Async:

```
import'dart:io';import'dart:convert';main()async=>print((await UTF8.decodeStream(stdin)).split("\n").fold(0,(p,e)=>p+int.parse(e)));

```

The async version is longer, easier to read, and faster than the sync version. It also works in checked mode. UTF8.decodeStream decodes the entire stream into a Future, await waits for this to finish and gives a String, the string is split by line into List, and finally the strings are folded into the final result.
> 1 votes

# Answer
## Lua, ~~59 bytes~~ 57 bytes

New code: 57 bytes

```
i,s=0,0;repeat i,s=i+s,io.read("*l")until not s print(i)

```

We initialize i and s to 0. For each iteration, we add s to i and load in a new s from stdin. Lua has implicit string -\> number coercions when doing numeric operations on a string.

---

Old code: 59 bytes

```
i=0;io.read("*a"):gsub(".-\n",function(g)i=i+g end)print(i)

```

Takes entire stdin and turns it into a string, gsubs over the entire string to extract lines, uses implicit number conversion and adds the lines to i, then prints i.
> 1 votes

# Answer
# Carrot, 6 bytes

```
#^A
+

```

Note the trailing space after the `+`.

Explanation:

```
#   //Set the stack to the entire input
^   //Convert to operations mode
A\n //Split the stack into an array on a new line
+   //Add all the arguments of the array together
    //Implicitly output the result

```
> 1 votes

# Answer
# Ly, 2 bytes

```
&+

```

Try it online!

A Ly builtin that would beat the accepted answer if it wasn't a 2-byte builtin...
> 1 votes

# Answer
# q/kdb+, 14 bytes

**Solution:**

```
sum"J"$(0:)`:f

```

**Example:**

```
q)system "cat f" / check contents of file f
"123"
,"5"
"99"
q)sum"J"$(0:)`:f
227

```

**Explanation:**

Read in the file called `f`, cast to longs, sum up:

```
sum"J"$read0`:f / ungolfed solution
            `:f / our input file f
       read0    / read in a file, break on newlines
   "J"$         / parse strings to longs
sum             / sum it up

```

**Bonus:**

The solution in **K4** is **10 bytes**. Eequivalent to `sum value each read0 `:f` in **Q**:

```
+/.:'0:`:f

```
> 1 votes

# Answer
## Wumpus, ~~11~~ 8 bytes

```
I+0i.
O@

```

Try it online!

### Explanation

As long as there are numbers left to read, the program loops through the first line:

```
I   Read a decimal integer from STDIN.
+   Add it to the top of the stack. Initially, the stack is empty, which adds
    the first number to an implicit zero.
0   Push 0.
i   Read the next byte. If there are numbers left, this will be a 10 (for the
    separating linefeed). Otherwise, we're at EOF and this gives -1.
.   Jump to (0, x), where x is the byte we just read, modulo 2 (because the
    program is 2 rows tall). So for a linefeed, this jumps to the beginning
    of the first line, and at EOF this jumps to the beginning of the second
    line.

```

Once we run out of numbers to add, control flow goes to the second line:

```
O   Print the sum as a decimal integer.
@   Terminate the program.

```
> 1 votes

# Answer
# Flobnar, ~~16~~ 12 bytes

<sup>-4 bytes thanks to @JoKing</sup>

```
+>p*
^@
>&06

```

Try it online! Requires the `-d` flag.

As a bonus, this works if no numbers are passed, and supports pretty much any separator other than digits and `-`.
> 1 votes

# Answer
# APL (Dyalog Unicode), 12 bytes

Complete program.

```
+/⍎⍕⊃⎕NGET⍞1

```

Try it online!

read filename from stdin

`⊃⎕NGET``1` get native file content as list of strings

stringify (puts two spaces between lines)

execute (as APL code)

`+/` sum
> 1 votes

# Answer
# Vyxal, 3 bytes

```
wJ∑

```

Try it Online!

### Explained

```
wJ∑
w   # list
 J  # merge
  ∑ # sum

```
> 1 votes

# Answer
# Sinclair ZX81 (16K only - probably\*) File size according to EightyOne - 163\** bytes (yes 163!) Byte count undetermined

Firstly, we should make our file, so using direct mode, type:

```
LET A=123
LET B=5
LET C=99

```

To make sure that they are there, print them to the screen, as follows:

```
PRINT A,,B,,C

```

This should appear on the display:

Now, to save this to file (as the variable stack is saved along with other important memory locations used by the interpreter), simply type:

```
SAVE "SUM"

```

If you're using a real ZX81 then press play and record on tape, whilst emulators like EightyOne will create a tape image for you.

Now clear the RAMs with:

```
RAND USR 0

```

or:

```
NEW

```

Now rewind the tape (or the emulator should auto-detect and start the virtual tape from the beginning), and type:

```
LOAD "SUM"

```

So our *file* is back in memories, so we need to add it together. Simply:

```
PRINT A+B+C

```

And the answer is:

\*I specify 16K because any less and the ZX81 will typically rearrange the memory and this could affect the var stack (mostly to do with collapsing the DFILE), as the DFILE is static with 16K then this should be less of an issue.

\**The ZX81 file is saving more than just the VAR stack of three whole variables above, and although each number appears to be an integer, the ZX81 is storing these variables as 24-bit floating point numbers rather than 1 byte integers.
> 0 votes

# Answer
# Anyfix, 4 bytes

```
ɦ€#S

```

### Explanation

```
ɦ€#S  Program
ɦ     Exhaust input; read into a list of lines
 €    Map:
  #        Parse to number
   S  Sum

```
> 0 votes

# Answer
# JavaScript (ES6), 27 bytes

```
s=>eval(s.split`
`.join`+`)

```

---

## Try it

```
f=
s=>eval(s.split`
`.join`+`)
oninput=_=>o.innerText=f(i.value);o.innerText=f(i.value=`123\n5\n99`)
```

```
textarea{font-family:sans-serif;height:100px;width:100px;}
```

```
<textarea id=i></textarea><pre id=o>
```

---

## Explanation

* Takes input as a multiline string via parameter `s`.
* Splits the string to an array on newlines.
* Joins the array to a string on `+`.
* Evals the string to give us the sum.

---

## Alternative, 23 bytes

If we could take each integer as an individual argument of our function then we could do this:

```
(...a)=>eval(a.join`+`)

```

---

## Alternative, 63 bytes

If we *have* to take a file name as input then use this version instead:

```
p=>fetch(p).then(r=>r.text()).then(s=>eval(s.split`
`.join`+`))

```
> 0 votes

# Answer
# Stax, 2 bytes

```
|+

```

Run and debug it

Also prints intermediate results, which doesn't appear to be disallowed
> 0 votes

# Answer
# C++, 98 bytes

```
#include<regex>
namespace std{int::main(){istream_iterator<int>a{cin},b;cout<<accumulate(a,b,0);}}

```

## Ungolfed

```
#include <iterator>
#include <numeric>
#include <iostream>

int main()
{
    std::istream_iterator<int> first{std::cin};
    std::istream_iterator<int> last{};
    std::cout << std::accumulate(first, last, 0);
}

```

We have `std::istream_iterator` to read input as whitespace-separated integers, and `std::accumulate` to add them up.
> 0 votes

# Answer
# Ahead, 13 bytes

```
~Ilj~#
 >K+O@

```

Try it online!
> 0 votes

# Answer
# Scheme, 48 bytes

```
(write(let l((x 0))(if(real? x)(+(l(read))x)0)))

```

Try it online! (Chicken Scheme, but this works on other schemes as well)

`(write ... )` write to STDOUT the result of

* `(let l ... )` looping special form named `l`
* + `((x 0))` initially declare `x` as `0`
* + `(if ... )` if
* + - `(real? x)` `x` is real, i.e. not EOF,
* + - `(+ ... )` add
* + - * `(l(read))` the result of this loop called with `x` set as the value read from STDIN
* + - * `x` with x
* + - `0` else give `0`
> 0 votes

# Answer
# Flurry, 24 bytes

```
[]{{}[<><<>()>]{}}[<>()]

```

### Run example

```
$ printf "11\n12\n13" | ./flurry -nii -c "[]{{}[<><<>()>]{}}[<>()]"
36

```

The integer input mode handles the input format requirement. Then it is straightforward reduction over the stack.

```
// Reduce the stack by running <pop and add to the current value>
// <stack height> times
main = height pop_add 0
height = []
pop_add = \x. x succ pop = {{}[<><<>()>]{}} // add x y = x succ y
0 = (SK) = [<>()]

```
> 0 votes

# Answer
# J-uby, 13 bytes

Port of Daniero’s Ruby answer.

```
:sum+Z|-:p^$<

```

Attempt This Online!
> 0 votes

# Answer
# , 18 bytes

```
1#.0".&>;:@stdin''

```

Attempt This Online!

```
1#.0".&>;:@stdin''
           stdin''  NB. self-explanatory
          @         NB. then
        ;:          NB. split into words, J boxes each int and each LF
      &>            NB. for every box
   0".              NB. eval the item as J code and fallback to 0
1#.                 NB. sum the result

```
> 0 votes

# Answer
# Thunno 2 `S`, 1 byte

```
¤

```

Attempt This Online!

Or, **2 bytes** flagless:

```
¤S

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, string, arithmetic
---


# Question
Title: Clearing the most significant bit from an integer
### Input

The input is a single positive integer `n`

### Output

The output is`n` with its most significant bit set to `0`.

### Test Cases

```
1 -> 0
2 -> 0
10 -> 2
16 -> 0
100 -> 36
267 -> 11
350 -> 94
500 -> 244

```

For example: `350` in binary is `101011110`. Setting its most significant bit (i.e. the leftmost `1` bit) to `0` turns it into `001011110` which is equivalent to the decimal integer `94`, the output. This is OEIS A053645.

# Answer
> 12 votes
# C (gcc), ~~49~~ ~~44~~ ~~40~~ 39 bytes

```
i;f(n){for(i=1;n/i;i*=2);return n^i/2;}

```

Try it online!

# Answer
> 10 votes
# Python 2, 27 bytes

```
lambda n:n^2**len(bin(n))/8

```

Try it online!

# 26 bytes

Unfortunately, this does not work for `1`:

```
lambda n:int(bin(n)[3:],2)

```

Try it online!

# Answer
> 10 votes
# 05AB1E, 5 bytes

```
.²óo-

```

Try it online!

Removing the most significant bit from an integer **N** is equivalent to finding the distance from **N** to the highest integer power of **2** lower than **N**.

Thus, I used the formula **N - 2floor(log2N)**:

* \- Logarithm with base **2**.
* `ó` \- Floor to an integer.
* `o` \- **2** raised to the power of the result above.
* `-` \- Difference.

# Answer
> 9 votes
# Jelly, 3 bytes

```
BḊḄ

```

Try it online!

# Explanation

```
BḊḄ  Main Link
B    Convert to binary
 Ḋ   Dequeue; remove the first element
  Ḅ  Convert from binary

```

# Answer
> 9 votes
# C (gcc) -- 59 bytes

```
main(i){scanf("%d",&i);return i&~(1<<31-__builtin_clz(i));}

```

This gcc answer uses only integer bitwise and arithmetic operations. No logarithms here! It may have issues with an input of 0, and is totally non-portable.

It's my first answer on this site, so I'd love feedback and improvements. I sure had fun with learning bitwise expressions.

# Answer
> 8 votes
# Java (OpenJDK 8), 23 bytes

```
n->n^n.highestOneBit(n)

```

Try it online!

Sorry, built-in :-/

# Answer
> 7 votes
# Husk, 3 bytes

```
ḋtḋ

```

Try it online!

**Explanation:**

```
    -- implicit input, e.g. 350
  ḋ -- convert number to list of binary digits (TNum -> [TNum]): [1,0,1,0,1,1,1,1,0]
 t  -- remove first element: [0,1,0,1,1,1,1,0]
ḋ   -- convert list of binary digits to number ([TNum] -> TNum): 94

```

# Answer
> 7 votes
# MATL, ~~8~~ 6 bytes

```
B0T(XB

```

Try it online!

Saved two bytes thanks to Cinaski. Switching to assignment indexing instead of reference indexing was 2 bytes shorter :)

### Explanation:

```
          % Grab input implicitly: 267
B         % Convert to binary: [1 0 0 0 0 1 0 1 1]
 0T(      % Set the first value to 0: [0 0 0 0 0 1 0 1 1]
    XB    % Convert to decimal: 11

```

# Answer
> 5 votes
# Python 3, 30 bytes

*-8 bytes thanks to caird coinheringaahing. I typed that from memory. :o*

```
lambda n:int('0'+bin(n)[3:],2)

```

Try it online!

# Answer
> 5 votes
# Python 2, 27 bytes

```
lambda n:n-2**len(bin(n))/8

```

Try it online!

# Explanation

```
lambda n:n-2**len(bin(n))/8  # Lambda Function: takes `n` as an argument
lambda n:                    # Declaration of Lambda Function
              len(bin(n))    # Number of bits + 2
           2**               # 2 ** this ^
                         /8  # Divide by 8 because of the extra characters in the binary representation
         n-                  # Subtract this from the original

```

# Answer
> 5 votes
# Ohm v2, 3 bytes

```
b(ó

```

Try it online!

# Answer
> 5 votes
# , 28 bytes

```
function(x)x-2^(log2(x)%/%1)

```

Try it online!

Easiest to calculate the most significant bit via `2 ^ floor(log2(x))` rather than carry out base conversions, which are quite verbose in R

# Answer
> 5 votes
## 32-bit x86 assembler, ~~10~~ ~~9~~ 7 bytes

Byte code:

```
0F BD C8 0F B3 C8 C3
```

Disassembly:

```
bsr ecx, eax
btr eax, ecx
ret
```

accepts and returns the value in the eax register.

Perform a reverse scan for the first set bit, and then reset that bit.

# Answer
> 4 votes
# Mathematica, 37 bytes

```
Rest[#~IntegerDigits~2]~FromDigits~2&

```

Try it online!

# Answer
> 4 votes
# JavaScript, ~~22~~ 20 bytes

*Saved 2 bytes thanks to ovs*

```
a=>a^1<<Math.log2(a)

```

Try it online!

### Another approach, 32 bytes

```
a=>'0b'+a.toString`2`.slice`1`^0

```

Try it online!

# Answer
> 4 votes
# J, 6 bytes

```
}.&.#:

```

Pretty simple.

### Explanation

```
}.&.#:
    #:  convert to list of binary digits
  &.    apply right function, then left, then the inverse of right
}.      behead

```

# Answer
> 4 votes
# APL (Dyalog), 10 bytes

Tacit prefix function.

```
2⊥1↓2∘⊥⍣¯1

```

Try it online!

`2∘⊥`… decode from base-2…
…`⍣¯1` negative one time (i.e. encode in base-2)

`1↓` drop the first bit

`2⊥` decode from base-2

# Answer
> 4 votes
# Ruby, 26 bytes

-7 Bytes thanks to Ventero. -2 Bytes thanks to historicrat.

```
->n{/./=~'%b'%n;$'.to_i 2}

```

# Answer
> 4 votes
# C (gcc), 38 bytes

Built-in in gcc used.

```
f(c){return c^1<<31-__builtin_clz(c);}

```

# Answer
> 4 votes
# ARM Assembly, ~~46~~ 43 bytes

(You can omit destination register on add when same as source)

```
clz x1,x0
add x1,1
lsl x0,x1
lsr x0,x1
ret

```

# Answer
> 4 votes
# Excel, ~~36~~ 31 bytes

`-5` bytes thanks to @IanM\_Matrix1

```
=BIN2DEC(MID(DEC2BIN(A1),2,99))

```

Nothing interesting.

# Answer
> 4 votes
**Excel, 20 bytes**

```
=A1-2^INT(LOG(A1,2))

```

# Answer
> 3 votes
# Mathematica, ~~21~~ 17 bytes

```
#-2^Floor@Log2@#&

```

Try it online!

This is my first Mathematica answer, feel free to tell me what have I screwed up.

**-4 bytes** thanks to @HyperNeutrino!

So as it turns out, someone made a similar program before, and sent it to the OEIS. However, keep in mind that the floor of a logarithm is basically defined as the number of digits of a number. This is just a coincidence, or rather a task simple enough that many people will get the same answer.

# Answer
> 3 votes
# APL (Dyalog Unicode), 9 bytes

```
⊢-2*∘⌊2⍟⊢

```

Try it online!

-1 byte thanks to Adam

# Answer
> 3 votes
# Pyth, 5 bytes

```
a^2sl

```

Test suite.

Explanation:

```
    l   Log base 2 of input.
   s    Cast ^ to integer (this is the position of the most significant bit.)
 ^2     Raise 2 to ^ (get the value of said bit)
a       Subtract ^ from input

```

# Answer
> 3 votes
## Alice, 8 bytes

```
./-l
o@i

```

Try it online!

### Explanation

```
.   Duplicate an implicit zero at the bottom of the stack. Does nothing.
/   Switch to Ordinal mode, move SE.
i   Read all input as a string.
l   Convert to lower case (does nothing, because the input doesn't contain letters).
i   Try reading all input again, pushes an empty string.
/   Switch to Cardinal mode, move W.
.   Duplicate. Since we're in Cardinal mode, this tries to duplicate an integer.
    To get an integer, the empty string is discarded implicitly and the input is
    converted to the integer value it represents. Therefore, at the end of this,
    we get two copies of the integer value that was input.
l   Clear lower bits. This sets all bits except the MSB to zero.
-   Subtract. By subtracting the MSB from the input, we set it to zero. We could
    also use XOR here.
/   Switch to Ordinal, move NW (and immediately reflect to SW).
o   Implicitly convert the result to a string and print it.
/   Switch to Ordinal, move S.
@   Terminate the program.

```

# Answer
> 3 votes
# Japt, 6 bytes

```
^2p¢ÊÉ

```

Try it online!

### Explanation

```
^2p¢ÊÉ
   ¢     Get binary form of input
    Ê    Get length of that
     É   Subtract 1
 2p      Raise 2 to the power of that
^        XOR with the input

```

## If input `1` can fail: 4 bytes

```
¢Ån2

```

Try it online!

**Explanation**: get input binary (`¢`), slice off first char (`Å`), parse as binary back to a number (`n2`).

# Answer
> 3 votes
# Octave, 20 bytes

```
@(x)x-2^fix(log2(x))

```

**Try it online!**

# Answer
> 3 votes
# PARI/GP, 18 bytes

```
n->n-2^logint(n,2)

```

Alternate solution:

```
n->n-2^exponent(n)

```

# Answer
> 3 votes
# CJam, 7 bytes

```
{2b()b}

```

Try it online!

Explanation:

```
{     }  Block:         267
 2b      Binary:        [1 0 0 0 0 1 0 1 1]
   (     Pop:           [0 0 0 0 1 0 1 1] 1
    )    Increment:     [0 0 0 0 1 0 1 1] 2
     b   Base convert:  11

```

Reuse the MSB (which is always 1) to avoid having to delete it; the equivalent without that trick would be `{2b1>2b}` or `{2b(;2b}`.

# Answer
> 3 votes
## Retina, ~~15~~ 13 bytes

```
^(^1|\1\1)*1

```

Try it online!

Input and output in unary (the test suite includes conversion from and to decimal for convenience).

### Explanation

This is quite easy to do in unary. All we want to do is delete the largest power of 2 from the input. We can match a power of 2 with some forward references. It's actually easier to match values of the form **2n-1**, so we'll do that and match one **1** separately:

```
^(^1|\1\1)*1

```

The group `1` either matches a single `1` at the beginning to kick things off, or it matches twice what it did on the last iteration. So it matches `1`, then `2`, then `4` and so on. Since these get added up, we're always one short of a power of 2, which we fix with the `1` at the end.

Due the trailing linefeed, the match is simply removed from the input.

# Answer
> 3 votes
# QBIC, ~~26~~ 18 bytes

Thank you, @DLosc, for saving 8 bytes!

```
≈q*2<=:|q=q*2]?a-q

```

## Explanation

```
≈     |  WHILE
 q*2       q doubled (this doesn't actually double q, but evaluates 2q)
    <=     is less than or equal to
      :    the input number (cmd line param, variable 'a')
q=q*2      double q (2, 4, 8, ...)
]          WEND
?a-q       PRINT a - q (ie 100 - 64 = 36)

```

# Answer
> 3 votes
# Haskell, ~~32~~ 29 bytes

```
(!1)
x!y|2*y>x=x-y|z<-2*y=x!z

```

Try it online!

-3 bytes thanks to @Laikoni

## Older solution, 32 bytes

```
f x=last[x-2^i|i<-[0..x],2^i<=x]

```

Try it online!

# Answer
> 3 votes
# Julia, 24 bytes

```
n->n-2^length(bin(n))÷2

```

Try it online!

`Int(floor(log2(n)))` is too long.

# Answer
> 2 votes
# Ruby, 31 bytes

```
->n{(0..n).find{|i|n-i&n+~i<1}}

```

Another bit-twiddling approach, might work better in a language where 0 is falsey. Finds the smallest number `i` such that `n-i` is a power of two, using the property of powers of two that they're the only numbers with no 1 bits in common with their predecessors.

# Answer
> 2 votes
# Japt, ~~6~~ 4 bytes

```
ì2_Å

```

Try it or run all test cases

```
ì2_Å     :Implicit input of integer
ì2       :Convert to base 2 digit array
  _      :Pass through the following function and convert back to decimal
   Å     :  Slice off the first digit

```

# Answer
> 2 votes
# Befunge, 22 bytes

```
&:1\v\*2\<
$%.@>2/:#^_

```

Try it online!

**Explanation**

Befunge doesn't have bit manipulation instructions, but we can instead use the mod command (`%`) to mask out the bits that we want to keep. So basically we calculate *n* % 2*b*, where *b* is the number of bits in the number minus one.

```
&:              Read n from stdin and make a copy to work with.
  1\            Push the initial mask value below it on the stack.

    v           Start a loop to determine the number of bits to mask.
    >2/         Divide the copy of n by 2.
       :#^_     Check if it has become zero.
        \<      If not, turn back and swap the mask value to the top of the stack.
      *2        Multiply the mask value by 2.
     \          Swap the modified copy of n back to the top of the stack.
    ^           Repeat the loop.

$               Once the copy of n becomes zero, we can exit the loop and drop it.
 %              We can then mod the original n with the mask value to get the result.
  .@            Finally output the result and exit.

```

# Answer
> 2 votes
## REXX, 52 bytes

```
b=x2b(d2x(arg(1)))
parse var b '1' b
say x2d(b2x(b))

```

Explanation:

1. Convert argument 1 into hex, then into binary representation.
2. Use *parse* to find first '1' in `b`, then store the rest of the string in `b` again.
3. Convert `b` into hex, then into decimal.

# Answer
> 2 votes
# IA-32 machine code, 12 bytes

Hexdump:

```
91 0f bd c8 33 d2 42 d3 e2 33 c2 c3

```

Corresponding assembly code, with inline disassembly:

```
91          xchg eax, ecx;
0f bd c8    bsr ecx, eax;
33 d2       xor edx, edx;
42          inc edx;
d3 e2       shl edx, cl;
33 c2       xor eax, edx;
c3          ret;

```

# Answer
> 2 votes
# Motorola 68020 Assembler, Unknown byte count, possibly 8

```
BFFFO D0{31:32}, D1 # Scan D0 from MSB to LSB, looking for the first set bit,
                    # from bit 31 for 32 bits
                    # Store this in D1
BCLR  D1, D0        # Clear the D1'th bit in D0

```

It's been a *long* time since I've done 680x0 assembler, and I can't find an online simulator. This takes a 32-bit input in D0, and returns it from there. It also trashes D1. Flags are also changed. Bad things will happen if D0 is zero; but the rules exclude that possibility.

# Answer
> 2 votes
16F48A Microcontroller, 155 bytes

```
IN Q,s0
MOVI s0,s1
MOVI s2,00
MOVI s3, 09

A: INC s2
SHR s1
JNZ A

B: DEC s3
DEC s1
JNZ B

C: MOVI s3,s4
SHL s0
DEC s3
JNZ C

D: DEC s4
SHR s0
JNZ D
OUT s0

```

explanation: This particular microcontroller takes inputs in binary, starting at the top of the code and working its way down. It can only use 9 registers (s0 through s8, but cannot output s8) and each of those registers can store 8 bits - again, in binary.

The first section takes the input and sets some values for later use.

section A shifts the input right, effectively removing bytes at the end, until it reaches zero, all the while, s2 is keeping track of how many shifts have taken place.

Section B then takes the amount of right shifts from 9, to determine how many times to shift left until the front byte that is a 1 has been removed.

Section C actually shifts left, but saves the amount of shifts to be able to shift right again.

Finally, section D shifts it right, to move it to the original position, minus the first 1.

# Answer
> 2 votes
# J, 8 Bytes

```
#.@}.@#:

```

### How it works:

```
  @  @       | Verb conjunction. Makes sure it isn’t executed as a hook
      #:     | Converts Number to binary, with no leading 0s (except if arg is 0)
   }.        | Drop leading 1
#.           | Convert back to int

```

Works for 1 and 0 since #. will convert an empty array into 0

# Answer
> 2 votes
# Vyxal, 3 bytes

```
bḢB

```

Try it Online!

### Explained

```
bḢB
b   # binary
 Ḣ  # remove first item
  B # binary back to base 10

```

# Answer
> 1 votes
# PowerShell, ~~66~~ 62 bytes

```
($c=[Convert])::ToInt32(0+($c::ToString("$args",2)|% su* 1),2)

```

Try it online!

*Thanks to cogumel0 for -4 bytes.*

Does exactly what it says on the tin. Takes input `$args`, `convert`s it `toString`, replaces the leading `1` using System.`su`bstring, then `convert`s it back `toInt32`. Output is implicit.

Yay for lengthy .NET calls.

---

Using the mathematical method that others are using, we can get down to

### PowerShell, ~~59~~ 56 bytes

```
param($a)$a-($m=[math])::pow(2,$m::floor($m::log($a,2)))

```

Try it online!

*Thanks to cogumel0 for -3 bytes.*

This takes input `$a`, takes the `log` in base `2`, then `floor`s that. The floor is needed because if we simply cast to an integer, PowerShell does Banker's Rounding which could lead to erroneous results. Then we take `2` to that `pow`er, and subtract that from `$a`. Output is implicit.

# Answer
> 1 votes
# Pyth, 6 bytes

```
it.BQ2

```

Try it online!

# Answer
> 1 votes
# Actually, 7 bytes

```
;╘L2ⁿ@-

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
bS1¸-JC

```

Try it online! or Try all test cases

```
b       # Convert to binary
 S      # Split
  1¸-   # Subtract 1 from the first element
     JC # Join and convert to decimal

```

---

`b¦C` works except for an input of `1`

# Answer
> 1 votes
# C# (.NET Core), 28+13=41 35 bytes

```
n=>n-(1<<(int)System.Math.Log(n,2))

```

Try it online!

### Acknowledgements

All credit for this answer goes to NieDzejkob; the mathematical approach is significantly better than binary string manipulation (below).

-6 bytes thanks @raznagul for seeing that `System` could just be included directly in the code, rather than as `using System;`.

# C# (.NET Core), 86+13=99 bytes

```
n=>{var t=Convert.ToString(n,2).Remove(0,1);return t.Length<1?0:Convert.ToInt32(t,2);}

```

Try it online!

+13 bytes for `using System;`

### UnGolfed

```
n=>{
    var t = Convert.ToString(n,2).Remove(0,1);
    return t.Length < 1 ? 0
                        : Convert.ToInt32(t,2);
}

```

Unfortunately `Convert.ToInt32` throws an exception on `""`, instead of returning `0`.

# Answer
> 1 votes
# Octave, 26 bytes

```
@(x)bi2de(de2bi(x)(2:end))

```

Try it online!

Note: The TIO-link uses `dec2bin` and `bin2dec` instead of `de2bi` and `bi2de`, because the communications package is not installed. The code works fine on Octave-online.net.

### Explanation:

```
@(x)                        % Anonymous function that takes a decimal number x as input
    bi2de(                  % Convert the following to decimal:
          de2bi(x)            % Convert x to decimal
                  (2:end)     % And take all elements except the first
                         )  % That's it.

```

# Answer
> 1 votes
# Perl 6, 17 bytes

```
{$_+&+^(1+<.msb)}

```

Try it online!

* `$_` is the argument to the function.
* `+&` is the bitwise AND operator.
* `+^` is the bitwise NOT operator.
* `+<` is the bitwise left shift operator.
* `.msb` returns the most significant bit of the function argument.

# Answer
> 1 votes
# C (gcc), 37 + 2 (`-lm`) = 39 bytes

```
f(x){x-=pow(2,floor(log(x)/log(2)));}

```

Try it online!

Saved some bytes thanks to a tip pointed out by @JustinMariner! This is my first proper C golf :-)

Since there is no plain **log2** built-in in C, I just (ab)used the fact that **loge(x) / loge(2) = ln(x) / ln(2) = log2(x)**.

---

### C (gcc), 34 bytes

```
f(c){c-=c^1<<31-__builtin_clz(c);}

```

Try it online!

# Answer
> 1 votes
# Add++,  ~~24~~  14 bytes

```
D,f,@,BBEP2$Bb

```

Try it online!

## How it works

```
D,f,@,   - Create a monadic function.
         - Example argument:   10
      BB - To binary; STACK = [[1 0 1 0]]
      EP - Dequeue;   STACK = [[0 1 0]]
      2  - Push 2;    STACK = [[0 1 0] 2]
      $  - Swap;      STACK = [2 [0 1 0]]
      Bb - From base; STACK = [2]

```

# Answer
> 1 votes
# CJam \- 8 bytes

```
ri2b(;2b

```

### Explanation

```
ri    # Reads input as integer
2b    # Convertion to base 2
(;    # Removes first element
2b    # Convertion from base 2

```

# Answer
> 1 votes
# Brain-Flak, 44 bytes

```
<>(()){((({}{}))){<>({}[()])}{}}<>([{}]{}<>)

```

Try it online!

### Explanation

The bulk of the modulus program is `{(({})){<>({}[()])}{}}`, which decrements two counters and resets the base counter every time it reaches zero. To deal with powers of two, the counter needs to be doubled each time it resets. The obvious way to do that is by replacing `(({}))` with `((({}){}))`, but this won't work since the doubling happens before the first iteration.

Instead, `((({}{})))` pushes the initial counter an additional time, and then adds these two copies together in the next iteration. In the first iteration, a 1 and an implicit 0 are added together to start with 1 as desired.

# Answer
> 1 votes
## Batch, 62 bytes

```
@set/an=%2+%2+1
@if %1 gtr %n% %0 %1 %n%
@cmd/cset/a%1-n/2-1

```

Edged out this 63-byte attempt:

```
@set/an=%2+%2+1,m=%1^^n+1
@if %m% gtr %n% %0 %1 %n%
@echo %m%

```

Which itself edged out this 64-byte port:

```
@set n=1
:l
@if %1 geq %n% set/an*=2&goto l
@cmd/cset/a%1-n/2

```

# Answer
> 1 votes
# Funky, ~~23~~ 20 bytes

```
n=>n~1<<math.log(2n)

```

~~I'm quite pleased with the result of this one.~~

~~Firstly, this calculates `math.floor(math.log(2,n))` incrementing a variable `i` whilst dividing `n` by two until it is \<1. Then, get's two to the power of that value, which removes all but the most significant bit from `n`. We can then get the answer by xoring this with `n`, which in funky is done with `~`.~~

Turns out the Javascript method works for this too, although `math.log2` can be replaced with `math.log(2`, because `2` and `n` are seen as two separate tokens in Funky, and thus is parsed like `2, n`

Try it online!

# Answer
> 1 votes
# Ruby, 22 bytes

```
->n{n^1<<Math.log2(n)}

```

Try it online!

# Answer
> 1 votes
# Bash, 27 bytes

```
bc -l<<<"$1-2^(l($1)/l(2))"

```

Try it online!

# Answer
> 1 votes
# PHP, ~~28~~ 25+1 bytes

```
<?=$argn^1<<log($argn,2);

```

Run as pipe with `-nF` or try it online.

# Answer
> 1 votes
# C 35 bytes

```
N;f(n){for(N=n;n&n-1;)n&=n-1;N-=n;}

```

Try it online!

> n&=n-1

Does the opposite of the problem statement, it clears the **least** significant bit.
I have a vague memory of there being a similar trick for most significant bit from seeing it on coding game but may remember wrong.

Recursive function, ~~45~~ 43 bytes

```
N;g(n){n&=(N=n&~-n)?g(N):n;}f(n){N=n-g(n);}

```

Try it online!

cleblancs code shortened to 34 bytes

```
i=1;f(n){for(;n/i/2;i*=2);n-=n^i;}

```

Try it online!

28 bytes, possibly cheating , using pointer instead of return

> f(\*n){\*n^=1\<\<(int)log2(\*n);}

Try it on ideone! , doesn't work on tio.run

# Answer
> 1 votes
# PHP, 38 bytes

```
<?=bindec(substr(decbin($argv[1]),1));

```

Straightforward way to do it. Convert the input to binary, remove the first character of the "string", convert back to decimal.

Try it online!

# Answer
> 1 votes
# Jq 1.5, 19 bytes

```
.-pow(2;log2|floor)

```

This is just a jq version of the formula `n - 2^Floor[Log2[n]]` from OEIS A053645

Try it online!

# Answer
> 1 votes
# Common Lisp, 40 bytes

```
(lambda(n)(- n(expt 2(floor(log n 2)))))

```

Try it online!

# Answer
> 1 votes
# Python, 32 bytes

```
lambda n:n-2**(n.bit_length()-1)

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), ~~74~~ 65 bytes

```
	I =INPUT
	J =1
R	J =GE(I - J) J + J :S(R)
	OUTPUT =I - J / 2
END

```

Try it online!

```
	I =INPUT			;*read in input
	J =1				;*set J to 1
R	J =GE(I - J) J + J :S(R)	;*if I-J>=0, double J and repeat, otherwise
	OUTPUT =I - J / 2		;*output I-J/2
END

```

# Answer
> 1 votes
# Python 2, 30 bytes

```
f=lambda n:n-1and 2*f(n/2)+n%2

```

Try it online!

Uses no built-in methods. 3 bytes longer than this solution using `bin`.

# Answer
> 1 votes
# Pip, 8 bytes

```
FB+@>TBa

```

Try it online!

### Explanation

```
     TBa  Convert cmdline arg to binary
   @>     Take all but the leftmost character
  +       Convert to number (required for turning "" into 0 so FB works properly)
FB        Convert from binary to decimal

```

# Answer
> 1 votes
# Manufactoria, 24 Bytes, 3 Blocks

```
c12:6f3;c12:8f3;p12:7f2;

?lvl=32&code=c12:6f3;c12:8f3;p12:7f2;&ctm=Level_Name!;Level_description!;:*;5;3;0;

```

# Answer
> 0 votes
# Perl 5, 23 + 1 (`-p`) = 24 bytes

```
$_-=2**int((log)/log 2)

```

Try it online!

# Answer
> 0 votes
# GolfScript \- 13 bytes

```
~2base(;2base

```

### Explanation

```
~      # Parse argument
2base  # Convertion to base 2
(;     # Cut away first byte
2base  # Convertion from base 2

```

# Answer
> 0 votes
# Tcl, 45 bytes

```
puts [scan [regsub 1 [format %b $argv] 0] %b]

```

Try it online!

# Answer
> 0 votes
## JavaScript (ES6), 23 bytes

```
f=x=>x^1&&f(x/2)*2|x&1

```

Not the shortest JS solution overall, but it beats the `.toString(2)` solution.

# Answer
> 0 votes
# C++, 63 bytes

```
[](decltype(0ul)x){auto y=x;return x^_BitScanReverse(&y,x)<<y;}

```

Usage (works in MS Visual Studio):

```
#include <intrin.h>
#include <stdio.h>

int main()
{
    auto h = [](decltype(0ul)x){auto y=x;return x^_BitScanReverse(&y,x)<<y;};

    printf("%d\n", h(10));
}

```

I added an artificial constraint on my code:

> It must use `_BitScanReverse`

The effect this had on my code is quite severe.

1. I used `decltype(0ul)` as an euphemism for `unsigned long`.
2. `_BitScanReverse` outputs its result by pointer, so I had to declare another `unsigned long` variable. This time, I did it with `auto y=x`.
3. The output of `_BitScanReverse` is "whether the input is nonzero", which is 1 (luckily).
4. The returned expression modifies `y` and then uses it, which is Undefined Behavior. There are no warnings though, and it works correctly.

# Answer
> 0 votes
# ARM (Thumb mode) machine code, 12 bytes

```
b0 fa 80 f1 01 31 88 40 c8 40 70 47

```

Disassembly:

```
fab0 f180       clz     r1, r0
3101            adds    r1, #1
4088            lsls    r0, r1
40c8            lsrs    r0, r1
4770            bx      lr

```

# Answer
> 0 votes
# C++, 42 bytes

```
int f(int n){return n-exp2((int)log2(n));}

```

# Answer
> 0 votes
# Pyth - 8 Bytes

```
ig.BQ2 2

```

Explanation:

```
ig.BQ2 2
i      2 Convert to base 2
 g   2   Slice from position 1 to the end (g slices from b-1)
  .B     Binary String representation of
    Q    Input

```

# Answer
> 0 votes
# Fig, \\$3\log\_{256}(96)\approx\\$ 2.469 bytes

```
Bpb

```

Try it online!

Same strategy as every other golflang.

# Answer
> 0 votes
# C (gcc), 27 bytes

Just realized this is a port of @xnor's python2 answer.

```
f(n){n=n>1?2*f(n/2)+n%2:0;}

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 5 bytes

```
ḃḣ0|Ḃ

```

Attempt This Online!

#### Explanation

```
ḃḣ0|Ḃ  # Implicit input      ->  100
ḃ      # Convert to binary   ->  "1100100"
 ḣ     # Remove first item   ->  "100100"
  0|   # Logical OR with 0   ->  "100100"
    Ḃ  # Convert to decimal  ->  36
       # Implicit output

```

---
Tags: code-golf, sequence, binary
---