34
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ May we take input as unary? \$\endgroup\$
    – user41805
    May 4, 2017 at 10:12
  • 4
    \$\begingroup\$ This would be, surprisingly, a lot easier if it was the other way around in some languages \$\endgroup\$ May 5, 2017 at 17:41
  • 5
    \$\begingroup\$ @MistahFiggins That's well known enough that I'm pretty sure OP did it like this on purpose. \$\endgroup\$ May 5, 2017 at 20:51

84 Answers 84

1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

Python, 20 bytes

lambda n:n+(n&1)*2-1
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Befunge 93, 18 bytes

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

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

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$ May 5, 2017 at 16:54
  • \$\begingroup\$ 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 \$\endgroup\$ May 5, 2017 at 17:01
  • \$\begingroup\$ @MistahFiggins, ah yes you are correct I was using 93. \$\endgroup\$
    – Daniel
    May 5, 2017 at 17:19
1
\$\begingroup\$

Ruby, 12 bytes

->n{-(-n^1)}
\$\endgroup\$
1
\$\begingroup\$

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|:-
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Casio-Basic, 27 bytes

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

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

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

MAWP, 18 bytes

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

Try it!

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 12 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Zsh, 14 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

><> (Fish), 10 bytes

:2%2*+1-n;

Try it

\$\endgroup\$
1
\$\begingroup\$

Thunno 2, 5 bytes

Ṅ1Æ^Ṅ

Attempt This Online!

Explanation

Ṅ1Æ^Ṅ  # Implicit input
    Ṅ  # -(        )
Ṅ      #   -input
  Æ^   #         ^
 1     #          1
       # Implicit output
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

C, 29 bytes

a(int b){return b%2?b+1:b-1;}
\$\endgroup\$
0
0
\$\begingroup\$

Jelly, 4 bytes

‘’Ḃ?

Try it online!

\$\endgroup\$
0
0
\$\begingroup\$

Batch, 20 bytes

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

Independently rediscovered @feersum's algorithm, honest!

\$\endgroup\$
0
\$\begingroup\$

CJam, 7 6 bytes

{(1^)}

Try it online!

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

\$\endgroup\$
0
0
\$\begingroup\$

C#, 34 11 bytes

n=>-(-n^1);

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

\$\endgroup\$
0
0
\$\begingroup\$

Swift, 29 bytes

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

Try it here

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.