g | x | w | all
Bytes Lang Time Link
024Tcl170505T164911Zsergiol
025Tcl250611T154303Zsergiol
030Tcl170505T164030Zsergiol
007J171012T064836ZJonah
068Kakoune + bc241215T225143ZJoshM
018Raku Perl 6 rakudo241212T210106Zxrs
007ARBLE241112T212958ZATaco
013AWK241112T210623Zxrs
032sed240414T184200Zguest430
005Uiua 0.11.0240415T034417ZTbw
002Vyxal240415T033216Zemanresu
017Alice240414T230958ZJulian
005Thunno 2230609T145024ZThe Thon
010><> Fish230602T232911Zchunes
010Braingolf v0.1170504T082932ZMayube
004Risky211009T042246ZDLosc
007TIBasic211010T003408ZYouserna
004Vyxal r210121T052522Zlyxal
031Python 3210409T194557ZSymmetr1
007BRASCA210129T103331ZSjoerdPe
015Factor210129T080657ZBubbler
056Boolfuck210129T051859ZEasyasPi
051brainfuck 8bit210120T233450ZEasyasPi
018Python 3210123T155627ZToxicCod
014Zsh210121T095829Zpxeger
040Lua210121T041207ZJ. А. de
006APL Dyalog Unicode201220T111345ZKamila S
005x8616 machine code200813T135655Z640KB
012Perl 5200813T115641ZDom Hast
004Japt200813T113855ZShaggy
007Keg200813T063802Zlyxal
018MAWP200813T062723ZRazetime
038tinylisp200813T050956ZDLosc
008Ly171012T073740ZLyricLy
027CasioBasic171012T061621Znumberma
024Common Lisp170717T144805ZRenzo
021Haskell170717T081617ZSergii M
017R170713T180344Zrunr
008Wise170506T144526ZWheat Wi
004170713T141914Ztotallyh
008braingasm170504T122653Zdaniero
035@REXX 35 Bytes170517T143841Ztheblitz
213Klein170516T232739ZWheat Wi
061Chip170510T151855ZPhlarx
012Juby170506T201833ZCyoce
012Ruby170506T201308ZCyoce
021Clojure170506T103057ZNikoNyrh
008x86 machine code170506T072219Zuser2330
068Python170505T183618Zpenalosa
011Befunge93170505T173934ZMercyBea
018Befunge 93170504T125758ZDaniel
006Actually170505T154627Zuser4594
010Pyth170505T111353Zkalsower
010QBIC170504T161919Zsteenber
027Excel VBA170505T072124ZStupid_I
009x86 Assembly170505T055325ZCody Gra
004Pyth170505T060014ZEsolangi
016Python170504T085903Zsagiksp
019Mathematica170504T083839Znumberma
010dc170504T195408ZDigital
020C170504T084754Zfeersum
072SAS170504T181337ZJ_Lard
017Groovy170504T180955ZJimwel A
020Python170504T133427ZWondercr
011Excel170504T175720Zpajonk
00705AB1E170504T173514Zsporkl
036BrainFlak170504T160412ZWheat Wi
017Fourier170504T154033ZBeta Dec
009Cubix170504T153136Zuser4854
015AWK170504T150907ZRobert B
011Cubix170504T143550ZLuke
006Japt170504T142749ZOliver
029Swift170504T140339ZCaleb Kl
011C#170504T084956ZKevin Cr
010JavaScript ES6170504T082603ZShaggy
006CJam170504T095327ZErik the
00405AB1E170504T093445ZOkx
012Javascript170504T084030ZMatthew
018Python3170504T083701ZYytsi
020Batch170504T092439ZNeil
336Stack Cats170504T090748ZMartin E
021Retina170504T091601ZNeil
010Java 8170504T084049ZKevin Cr
015PHP170504T090009Zuser6395
007MATL170504T085419ZLuis Men
020Python170504T083504Znumberma
003Jelly170504T083352ZLeaky Nu
004Jelly170504T083022ZErik the
029C170504T083133Zegonr

Tcl, 24 bytes

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

Try it online!


Tcl, 23 bytes

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

Try it online!

Tcl, 25 bytes

proc s n {expr $n--1**$n}

Try it online!

Tcl, 30 bytes

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

Try it online!

J, 7 bytes

1-@XOR-

Try it online!

This version thanks to south.

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!

Kakoune + bc, 68 bytes

itry %{exec "/[13579]$<ret>a+1<c-v><esc>"}<ret><esc>hGGypf1t]c02468<esc>f+;r-f<ret>;GGd:<c-r>"<ret>x|bc<ret>

exec is a builtin alias for execute-keys

we search for both even and odd numbers but we use the try %{exec <search and do stuff>} to fail if the search fails and not do any of the other operations.
We append a +1 to odd numbers and a -1 to even numbers. Then the resulting expression is piped to bc (a basic command line calculator utility)

roughly equivalent to this script

try %{exec "/[13579]$<ret>a+1<esc>"} # search for odd and append +1
try %{exec "/[02468]$<ret>a-1<esc>"} # search for even and append -1
exec "x|bc<ret>"                     # pipe resulting expression to bc

but to save characters the first line is written, then copied and modified to be the second one and then the final thing is cut and pasted as a command to do the appending

Raku (Perl 6) (rakudo), 18 bytes

f($x){$x-(-1)**$x}

Attempt This Online!

ARBLE, 7 bytes

-(-n~1)

Try it online!

Humble port of the C answer

AWK, 13 bytes

$0+=$0%2?1:-1

Try it online!

$0+=   # set output
$0%2   # parity
?1:-1  # add or subtract

sed, 33 32 bytes

s/^/%/    #insert % at begining
s/../&%/g #put % after char pairs
s/.%.$//  #if odd, delete 2 chars
s/%//g    #remove the percents

Try it online!

takes input as any unary char other than %.

Uiua 0.11.0, 5 bytes SBCS

-ⁿ,¯1

Try on Uiua Pad!

Explanation

,¯1 # n, -1, n 
ⁿ   # (-1)^n, n
-   # n - (-1)^n

Vyxal, 2 bytes

Ǎ-

Try it Online!

 - # n -
Ǎ  # -1 ^ n

Alice, 17 bytes

/O\.2%2v
@M/+t* <

Try it online!

/M\.2%2*t+/O@
/M\              # Reads an argument and put it on the slack
   .2%2*t+       # Calculates input + (input mod 2) * 2 - 1
          /O@    # Prints the top of the stack and exit

Thunno 2, 5 bytes

Ṅ1Æ^Ṅ

Attempt This Online!

Explanation

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

><> (Fish), 10 bytes

:2%2*+1-n;

Try it

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.

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

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

Vyxal r, 4 bytes

‹ue+

Try it Online!

Me and the boys porting risky be like

Explained

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

Python 3, 36 31 bytes

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

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

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!

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

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.

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)

Zsh, 14 bytes

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

Try it online!

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

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.

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!

Perl 5, 12 bytes

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

Try it online!

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

Keg, -hr, 7 bytes

:2%[;|⑨

Try it online!

MAWP, 18 bytes

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

Try it!

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.

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

Casio-Basic, 27 bytes

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

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

Common Lisp, 24 bytes

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

Try it online!

Haskell, 21 bytes

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

I have no idea why I'm doing this xD

R, 17 bytes

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

where n=scan() takes the digit value.

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

-::^~-^-

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

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.

@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

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.

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

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

Ruby, 12 bytes

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

Clojure, 21 bytes

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

It is quite difficult to get creative with this.

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

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.

Graph demonstrating function

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!

Befunge 93, 18 bytes

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

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

Actually, 6 bytes

;0Dⁿ@-

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

Explanation:

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

Pyth, 10 bytes

+Q?%Q2 1_1

Try it online

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

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

Excel VBA 27 bytes

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

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   

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

Python, 16 bytes

lambda x:-(-x^1)

Try it online!

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.

dc, 10

?d2%2*+1-p

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

Try it online.

C, 20 bytes

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

Try it online.

SAS, 72 bytes

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

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.

Python, 20 bytes

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

Excel, 11 bytes

=A1-(-1)^A1

Assumes input in A1.

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.

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

{}({}{})

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

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

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

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

Japt, 6 bytes

n ^1 n

Try it online!

Swift, 29 bytes

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

Try it here

C#, 34 11 bytes

n=>-(-n^1);

Port of @feersum's amazing C answer.
Try it here.

JavaScript (ES6), 14 13 12 10 bytes

n=>-(-n^1)

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

CJam, 7 6 bytes

{(1^)}

Try it online!

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

05AB1E, 4 bytes

(1^(

Try it online!

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>

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

Batch, 20 bytes

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

Independently rediscovered @feersum's algorithm, honest!

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.

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.

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

PHP, 15 bytes

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

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
  

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.

Jelly, 3 bytes

-*ạ

Try it online!

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

Jelly, 4 bytes

‘’Ḃ?

Try it online!

C, 29 bytes

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