## Swap the parity

22

3

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

May we take input as unary? – user41805 – 2017-05-04T10:12:23.003

2This would be, surprisingly, a lot easier if it was the other way around in some languages – MildlyMilquetoast – 2017-05-05T17:41:44.990

3@MistahFiggins That's well known enough that I'm pretty sure OP did it like this on purpose. – Ørjan Johansen – 2017-05-05T20:51:26.360

24

# C, 20 bytes

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


5f(x){x=-(-x^1);} – Leaky Nun – 2017-05-04T08:50:34.363

7@LeakyNun I am not writing a function lacking a return statement. – feersum – 2017-05-04T09:08:17.290

@feersum When I saw this question I knew that this approach was the way to go. – Neil – 2017-05-04T09:09:16.537

1@feersum Yes you do write one, since assigning to the first argument is equivalent to using a return statement. – Erik the Outgolfer – 2017-05-04T09:15:20.367

18@EriktheOutgolfer No. Nope. Nuh-uh. No. – feersum – 2017-05-04T09:24:48.890

@feersum Try it online! (are you serious?)

– Erik the Outgolfer – 2017-05-04T09:38:36.240

1@EriktheOutgolfer I don't think it's a good idea to omit the return statement. It invokes undefined behavior and while it may work sometimes it's very fragile (for example on my machine compiling with gcc -O3 it breaks) – Sisyphus – 2017-05-04T09:59:10.350

10@Sisyphus But this is [tag:code-golf], and it works on my TIO link, so it's valid. – Erik the Outgolfer – 2017-05-04T10:07:08.397

7@EriktheOutgolfer What I am saying is that your statement ("assigning to the first argument is equivalent to a return statement" ) is factually incorrect. Whether such code may generate a working answer under certain circumstances is another question (which I have addressed in my first comment by stating that I plan not to post any such code). – feersum – 2017-05-04T10:16:43.833

8@EriktheOutgolfer If an answer relies on implementation specific behavior, it should specify an implementation. This answer doesn't, so that code would be invalid. – Sisyphus – 2017-05-04T10:44:04.107

18

## 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.

1

Are flags always counted with the additional space, I don't think I've seen other answers using flags (like Perl) do that? EDIT: Ok nvm, found the relevant meta post. "I count those as a difference in character count to the shortest equivalent invocation without them." ... "perl -nle 'stuff' is 2 characters more than perl -e 'stuff', so it counts for 2 more characters". So (space)-n is 3 bytes more than without the flag.

– Kevin Cruijssen – 2017-05-04T09:29:36.830

@KevinCruijssen It depends on how many bytes you actually need to add to a usual invocation. In Perl and many other production languages, you can invoke the code with -e "code" and then insert additional flags before the e, e.g. -pe "code". Then the -p flag is only one byte. However, Stack Cats has no such -e argument, so you always need to add the full <sp>-n to the command, and hence it's three bytes. – Martin Ender – 2017-05-04T09:31:14.207

12

# 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 DECrement 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 NEGation with an INCrement:

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


Wouldn't just dec eax; xor eax, 1; inc eax work and save one byte more? – Ilmari Karonen – 2017-05-05T12:51:19.140

11

# Jelly, 3 bytes

-*ạ


Try it online!

Pseudocode: abs((-1)**n - n)

I was actually planning to (ab)use -1. – Erik the Outgolfer – 2017-05-04T08:48:16.870

Sorry for that. – Leaky Nun – 2017-05-04T08:48:59.393

There isn't any sorry, well done! I didn't figure out how to do it quickly enough... – Erik the Outgolfer – 2017-05-04T08:50:05.440

11

# 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...

10

# Python, 16 bytes

lambda x:-(-x^1)


Try it online!

3Brute forcing doesn't find any shorter solution using characters in "x+-012~|&^()*/%". – xnor – 2017-05-04T09:00:33.507

@xnor Good thing I got it then! – sagiksp – 2017-05-04T09:02:00.687

1And it looks like there are no other same-length solutions except the trivial rearrangement -(1^-x). – xnor – 2017-05-04T09:18:11.573

8

# 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


1Nice! Like it ! – Stewie Griffin – 2017-05-04T09:00:31.257

6

# 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 [non-competing]

.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.

However v0.2 was released after the challenge, so this one's non-competing

5Congratulations on your new language! – Leaky Nun – 2017-05-04T08:30:06.803

Does .1<2,%?+:- do what I think it does? – Neil – 2017-05-04T09:31:43.107

@Neil not quite, you'd need a comma before the - to make it perform the operation the correct way around, in which case it'd still be the same length as my answer – Skidsdev – 2017-05-04T09:33:26.717

@Mayube I was expecting the < to rotate the 1 below the input, so that it would be in the correct place already. – Neil – 2017-05-04T09:34:45.273

@Neil if the input is an even number, by the time it reaches the - the stack looks like this: [n,1] braingolf operators are reversed, so it would perform 1 - n, which would result in -(n-1), wheras the desired result is simply n-1 – Skidsdev – 2017-05-04T09:37:08.843

Of course if I updated braingolf to not reverse operators by default (which I should), this could be shortened to 9 bytes by removing both commas, but then the shorter answer would be non-competing. I might do that anyway though – Skidsdev – 2017-05-04T09:38:17.940

Well, if you're going to do that, then never mind, but my point is, my stack is the opposite way around to your stack, so I don't need the ,. – Neil – 2017-05-04T09:44:24.640

@Neil Nope, in your code the stack right before the - is [n,1], if you hit the v0.1 TIO link you can test it by inserting = anywhere in the code to print the stack at that point – Skidsdev – 2017-05-04T09:45:57.487

Ah, I misunderstood the way the > and < operators worked, so .1>2,%?+:- is now the correct BrainGolf v0.1 answer. – Neil – 2017-05-04T09:49:25.413

@Neil So it is! – Skidsdev – 2017-05-04T09:50:55.607

By the way, I think , would be more useful as an operator that exchanges the top two elements of the stack. – Neil – 2017-05-04T10:00:00.993

@Neil yeah definitely agree – Skidsdev – 2017-05-04T10:08:26.137

5

# 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


4

## 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.

3

# JavaScript (ES6), 141312 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


3

# 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>

>

• you don't need to include the semicolon; 2. x=>x-(-1)**x
• < – Leaky Nun – 2017-05-04T08:43:38.530

Why the |0? Both solutions look as if they should automatically convert strings to numbers. (For the first solution, if you want to avoid decimals, use <input type=number>.) – Neil – 2017-05-04T09:27:25.667

@Neil Thanks for notifying me! – Matthew Roh – 2017-05-04T09:28:14.947

3

# PHP, 15 bytes

<?=-(-$argn^1);  2How do I run this? I'm trying to test whether the ; is required, and have tried using a .php file and also echoing directly into php (php7 cli.) Each time I'm told that $argn is an undefined variable. – Andrakis – 2017-05-04T11:51:39.803

2@Andrakis With the F flag and a pipeline: echo 42 | php -F script.php. – user63956 – 2017-05-04T13:36:21.790

2

# 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.

1Use a lambda: lambda n:[n-1,n+1][n%2] – Leaky Nun – 2017-05-04T08:35:27.783

Ah yes, so it was shorter in this case. Done, thanks! – numbermaniac – 2017-05-04T08:36:15.953

2

# Mathematica, 22 19 bytes

Saved 3 bytes thanks to Greg Martin!

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


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


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.

2You can save three bytes by abusing Mathematica's [[0]] capability: #-1[-1][[#~Mod~2]]&. – Greg Martin – 2017-05-04T18:34:57.773

That's insane, never would've thought of that. Done, thanks! – numbermaniac – 2017-05-05T03:40:02.947

2

# 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

# 05AB1E, 4 bytes

(1^(


Try it online!

Alternative 4 byte solution: Try it online!.

But Èi>ë< is so pretty ;_;. – Magic Octopus Urn – 2017-07-17T16:51:08.190

2

# 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:
O  # Output the number
@ # Terminate the program


2

# 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

{}({}{})


2

# 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 -.

-::^~-^-


1

# 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.

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

## Befunge 93, 18 bytes

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


I am not done golfing this yet (I hope).

Golfing tips: Befunge 98 has the ability to use kv (or jv if it is strictly 1 or 0) instead of #v_. Also, if you are using Try it online (and I recommend it), you can end the program with another & (although it will take 60 seconds), so you can get rid of the @ on the first line if you use that. here is the full list of commands for Befunge-98, although they might not all be correctly implemented in TIO, like & ending the program instead of reversing on EOF.

– MildlyMilquetoast – 2017-05-05T16:54:54.160

Also, It looks like you're using befunge 93 instead of 98, which has fewer commands. You might want to fix your link name if it is indeed 93 and not 98 – MildlyMilquetoast – 2017-05-05T17:01:09.850

@MistahFiggins, ah yes you are correct I was using 93. – Daniel – 2017-05-05T17:19:24.840

1

# Python, 20 bytes

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


1

# Japt, 6 bytes

n ^1 n


Try it online!

1

# Ruby, 12 bytes

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


1

# R, 17 bytes

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


where n=scan() takes the digit value.

I think you need -(-1)^n rather than +(-1)^n since we need to return n-1 if n is even – Giuseppe – 2017-07-13T18:25:55.787

@Giuseppe oh, yes, of course, foolish mistake – Nutle – 2017-07-13T20:18:46.103

1

# Casio-Basic, 27 bytes

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


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

0

# Jelly, 4 bytes

‘’Ḃ?


Try it online!

@LeakyNun thanks for testcases – Erik the Outgolfer – 2017-05-04T09:44:46.130

0

# C, 29 bytes

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


0

# C#, 34 11 bytes

n=>-(-n^1);


0

## Batch, 20 bytes

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


Independently rediscovered @feersum's algorithm, honest!

0

# CJam, 7 6 bytes

{(1^)}


Try it online!

-1 thanks to Martin Ender. ...............OOOO

0

# 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.

0

# Swift, 29 bytes

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


Try it here

0

# 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. :) 0 # 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 ## 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 # 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 ## Excel, 11 bytes =A1-(-1)^A1  Assumes input in A1. 0 # 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. 0 ## SAS, 72 bytes %macro t(n);%put%eval(&n+%sysfunc(ifn(%sysfunc(mod(&n,2)),1,-1)));%mend;  0 # dc, 10 ?d2%2*+1-p  Uses the same formula as @TuukkaX's python answer. 0 ## 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  Welcome to Pyth! Hope you'll have a great time golfing in Pyth. – Leaky Nun – 2017-05-05T06:02:23.333 0 ## Excel VBA 27 bytes [a2]=iif(n mod 2=0,n-1,n+1)  I don't think taking input from a variable is legal on PPCG (the question's worded a bit weirdly, but I don't think that permits it). You'd have to write a program or function. (Also, although it's optional, I recommend writing an explanation or brief description of how your code works; posts like this one which are just a code block have a tendency to set off the low-quality-posts filter, which can cause trouble sometimes.) – None – 2017-05-05T11:11:40.450 0 ## Pyth, 10 bytes +Q?%Q2 1_1  Try it online As simple as using modulo of input with 2 and the ternary operator. Golfed – Leaky Nun – 2017-05-05T11:14:45.553 – Leaky Nun – 2017-05-05T11:15:20.353 How long did I search for standard short circuit D: only found reverse.. nice one though – kalsowerus – 2017-05-05T11:16:09.153 Welcome to PPCG, and welcome to Pyth. Hope you have a great time golfing in PPCG with Pyth. – Leaky Nun – 2017-05-05T11:19:34.233 0 # Actually, 6 bytes ;0Dⁿ@-  Explanation: ;0Dⁿ@- ;0Dⁿ (-1)**n @- n - (above)  0 # Tcl, 30 proc s n {expr$n%2?$n+1:$n-1}


demo

0

 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

# 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

# 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

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
even:
dec al


0

## Clojure, 21 bytes

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


It is quite difficult to get creative with this.

0

# 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|:-


0

# 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


0

# 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.

0

@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

# ,,,, 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

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


I have no idea why I'm doing this xD

0

# Common Lisp, 24 bytes

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


Try it online!

0

# J, 9 bytes

(22 b.)&1


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

Try it online!

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

Try it online!

0

# Ly, 8 bytes

n:2%2*+,


Try it online!

Explanation:

n:2%2*+,

n        # take input
:2%     # modulo two
2*   # multiply by two
`