55
\$\begingroup\$

Task

Given a non-negative integer n, output 1 if n is 0, and output the value of n otherwise.

Input

A non-negative integer.

  • If you would like to accept the string as input, the string would match the following regex: /^(0|[1-9][0-9]*)$/, i.e. it must not have any leading zeroes, except when it is 0.
  • If you accept a real integer as input, you may assume that the integer is within the handling capability of the language.

Output

A positive integer, specified above. Leading zeroes are not allowed. Your output should match the regex /^[1-9][0-9]*$/.

Testcases

input output
    0      1
    1      1
    2      2
    3      3
    4      4
    5      5
    6      6
    7      7

Scoring

This is , so shortest answer in bytes wins.

Standard loopholes apply.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ You should probably put a link to the TNB CMC, since that's where this challenge came from. \$\endgroup\$
    – mbomb007
    Commented May 3, 2017 at 20:53
  • \$\begingroup\$ Does the answer need to be a full function, or can it be the body? \$\endgroup\$ Commented May 3, 2017 at 20:58
  • 1
    \$\begingroup\$ @CalebKleveter The default rule in PPCG is that the answer is either a function or a full program, but not snippets. \$\endgroup\$
    – Leaky Nun
    Commented May 4, 2017 at 1:56
  • \$\begingroup\$ Can we print the output with a leading zero? \$\endgroup\$
    – MD XF
    Commented Dec 26, 2017 at 21:54
  • \$\begingroup\$ @MDXF yes, you can. \$\endgroup\$
    – Leaky Nun
    Commented Dec 26, 2017 at 22:30

160 Answers 160

4
\$\begingroup\$

R, 13 bytes

n=scan();n+!n

Here, scan is used to read the input value n. The negation of n (i.e., !n, 0 or 1) is added to n.

\$\endgroup\$
4
\$\begingroup\$

Braingolf, 8 bytes

!?_:1_;

Explanation:

 ?       If last element on stack > 0
!        Prevent if check from consuming last element on stack
  _      Pop last element on stack and print
   :     Else
    1    Add int literal 1 to end of stack
     _   Pop last element on stack and print
      ;  Prevent automatic pop of last element on stack
\$\endgroup\$
3
  • \$\begingroup\$ Is this your language? \$\endgroup\$
    – Leaky Nun
    Commented May 3, 2017 at 14:55
  • 1
    \$\begingroup\$ Yup, literally got bored at work today and decided to make a language. As you can tell it's very WIP, this is one of the only challenges that it can do beyond simply printing a string \$\endgroup\$
    – Mayube
    Commented May 3, 2017 at 14:55
  • 1
    \$\begingroup\$ Congratulations on your new language! \$\endgroup\$
    – Leaky Nun
    Commented May 3, 2017 at 14:56
4
\$\begingroup\$

Ruby, 11 bytes

->n{n|1>>n}
\$\endgroup\$
4
\$\begingroup\$

GCC command line, 9 bytes

-Df(x)x?:

Try it online!

-D in GCC checks if the following content has an =; if not, it add the code

#define <followed_content> 1

which in this case turns into

#define f(x)x?: 1
\$\endgroup\$
2
  • \$\begingroup\$ On meta I gave a common solution but here I give a pointed one \$\endgroup\$
    – l4m2
    Commented Dec 20, 2017 at 18:20
  • 1
    \$\begingroup\$ Can the downvoter leave a comment? I find this very creative. \$\endgroup\$
    – MD XF
    Commented Dec 26, 2017 at 21:36
4
\$\begingroup\$

Sinclair ZX81/Timex TS1000/1500 BASIC ~19 tokenized BASIC bytes

 1 INPUT A
 2 PRINT A+NOT A

This is a more efficient solution than the one below; essentially it takes the NOT value of A (which would be zero in all cases but zero) and adds that to the value of A.

Old answer:

Sinclair ZX81/Timex TS1000/1500 BASIC, ~31 tokenized BASIC bytes

 1 INPUT A
 2 IF NOT A THEN LET A=NOT A
 3 PRINT A

This takes a numeric input from the user and will display 1 if zero is entered by making A NOT A; otherwise it does nothing and displays the numeric value.

\$\endgroup\$
4
\$\begingroup\$

Forte, 25 bytes

9LET0=1:INPUT2:PRINT2:END

Try it online!

Explanation

Clearly, the best way to approach this challenge is to define 0 to be 1. Problem solved.

Seriously. That's exactly what this program does.

9          Line number (doesn't matter as long as it's not 0 or 2)
 LET 0=1   Redefine 0 to be 1; all future occurrences of 0 will evaluate as 1
 INPUT 2   Redefine 2 to be a number read from input; all future occurrences of 2 will
           evaluate as the input number, though of course if that number was 0 it
           actually evaluates as 1
 PRINT 2   Print that number
 END       End the program
\$\endgroup\$
3
\$\begingroup\$

Taxi, 517 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Knots Landing.Go to Knots Landing:n 2 r 2 r 1 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 1 l 2 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Formatted for humans:

Go to Post Office:w 1 l 1 r 1 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s 1 l 1 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:n 1 l 1 l 2 r.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Knots Landing.
Go to Knots Landing:n 2 r 2 r 1 l.
Pickup a passenger going to Addition Alley.
Go to Addition Alley:w 1 r 1 l 2 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:n 1 r 1 r.
Pickup a passenger going to Post Office.
Go to Post Office:n 1 l 1 r.

The key location is Knots Landing which performs the NOT operation so 0 returns 1 and all other numbers return 0. Now, you can go to Addition Alley to add the result from Knots Landing to the original input.

\$\endgroup\$
3
\$\begingroup\$

x86-64 Assembly, 10 9 bytes

Following the standard System V AMD64 calling convention, this function accepts a 32-bit unsigned integer parameter via the EDI register, and returns the result via the EAX register:

89 F8  |     mov   eax, edi    ; move parameter from EDI to EAX
85 C0  |     test  eax, eax    ; test input and set flags
75 01  |     jnz   Finished    ; if input is non-zero, then jump to end
FF 40  |     inc   eax         ; otherwise, input is 0, so increment it to 1
       |  Finished:
C3     |     ret               ; return, leaving result in EAX

x86-32 Assembly, 8 bytes

We could also write this as 32-bit code, since we're only dealing with 32-bit values.

The nice thing about this is that the INC instruction becomes only 1 byte in length. (In 32-bit mode, inc eax can be encoded simply as 40. In 64-bit mode, 40 is interpreted as a REX prefix, so the leading FF is needed. See Intel's documentation for this instruction.)

The caveat is that most 32-bit calling conventions pass parameters on the stack, rather than in registers, and loading a value from the stack (memory) takes many more bytes. If we can be allowed a __fastcall-style calling convention that passes parameters in registers (supported by virtually all C compilers, so not really cheating, just a bit less standard), then the integer parameter is passed in ECX and we get the following code, for a total of 8 bytes:

89 C8  |     mov  eax, ecx
85 C0  |     test eax, eax
75 01  |     jnz  Finished
40     |     inc  eax
       |  Finished:
C3     |     ret
\$\endgroup\$
5
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$
    – Justin
    Commented May 5, 2017 at 15:35
  • \$\begingroup\$ xchg eax, edi is only 1 byte and is fine since you don't need to keep a copy of the value. Or use a calling convention like GCC's regparm (-mregparm=3) that passes the first arg in EAX already. Tips for golfing in x86/x64 machine code \$\endgroup\$ Commented Jan 28, 2021 at 3:52
  • \$\begingroup\$ Or following an ARM machine-code answer's idea, mov eax, edi / neg edi (setting CF for any non-zero input) / sbb eax, -1 to add 1 or 0 (-(CF + -1)). Unfortunately no shorter unless we can use sbb al, -1 (2 bytes) \$\endgroup\$ Commented Jan 28, 2021 at 3:56
  • \$\begingroup\$ Thanks, @Peter, for the review. I wrote this answer back before I knew it was legitimate to adopt custom calling conventions in assembly answers. I probably won't update it myself at this point; feel free to do so without stepping on my toes. Or post a separate answer. \$\endgroup\$ Commented Jan 28, 2021 at 4:11
  • \$\begingroup\$ There's already a quite clever 5-byte x86 answer with the function entry point in the middle of a block, using jecxz to run an inc ecx, taking full advantage of fastcall and of 1-byte xchg \$\endgroup\$ Commented Jan 28, 2021 at 4:17
3
\$\begingroup\$

x86 opcode, 6 5 bytes

       41                         INC     ECX
entry: E3 FD                      JECXZ   SHORT $-1
       91                         XCHG    EAX,ECX
       C3                         RETN

ECX -> EAX

\$\endgroup\$
4
  • \$\begingroup\$ You'll need to add a length in bytes, so other users can tell how long it is. Generally assembly or byte/op-code languages are measured in the size of the instructions the source represents. \$\endgroup\$
    – Οurous
    Commented Dec 18, 2017 at 21:15
  • \$\begingroup\$ fixed. forgot. ` ` \$\endgroup\$
    – l4m2
    Commented Dec 18, 2017 at 21:26
  • \$\begingroup\$ Damn, I just came up with E3 01 49 41 C3. \$\endgroup\$
    – user99151
    Commented Jan 28, 2021 at 4:48
  • \$\begingroup\$ @2x-1 yeah if returning in ECX it can be 1B shorter \$\endgroup\$
    – l4m2
    Commented Feb 4, 2021 at 9:11
3
\$\begingroup\$

Java 8, 9 bytes

n->n|1>>n

Try it online.

C# .NET, 9 bytes

n=>n|1>>n

Try it online.

Different approach (and 1 byte shorter) than the existing Java/C# .NET answers. (Also works with negative inputs.)

Explanation:

i->       // Method with integer as both parameter and return-type
  i|      //  Return the input bit-wise OR-ed with:
    1>>i  //  1 bit-wise right-shifted by the input

1>>i will be 1 when the input is 0, and 0 for every other input.
0|1 for input 0 will therefore result in 1, and n|0 for every other input will therefore result in n.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ See? You're getting better at bitwise operations ;-) \$\endgroup\$ Commented Apr 13, 2018 at 9:30
  • 1
    \$\begingroup\$ These two are also polyglots with Kotlin, Scala, and a ton of other languages :) \$\endgroup\$
    – user
    Commented Jun 4, 2021 at 21:50
3
\$\begingroup\$

Zsh, 13 bytes

<<<$[$1?$1:1]

Try it online!

Bash, 15 bytes

echo $[$1?$1:1]

Try it online!

Dash (or other POSIX-compliant shell), 17 bytes

echo $(($1?$1:1))

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Binary Lambda Calculus, 2.125 Bytes

00010110 00110001 0

Translation into lambda calculus:

\n. n (\x. n) (\x. x)
\$\endgroup\$
3
\$\begingroup\$

Labyrinth, 6 bytes

?"1
@!

Try it online!

?   Take number input and push it
"   No-op, but a 3-way junction:
    If top is 0, go straight
1     Convert the 0 to 1 and bounce off the dead end
"     Enter the junction again, turn right (reflected to south)
!@    Pop and print as number, turn around the corner and halt

    Otherwise, top is positive; turn right
!@    Pop and print as number and halt
\$\endgroup\$
3
+100
\$\begingroup\$

Vyxal, 2 bytes

¬+

Straightforward answer:

¬  # nots the input (x == 0 ? 1 : 0)
+  # adds it to the input

Try it Online!

\$\endgroup\$
3
\$\begingroup\$

Lolwho.Cares, 62 bytes

*2*+21*1*+21010,**>*2+00210`v
0 ^02210012+*1*<  ^<0210002<<
321

Old version:

*2*+210*1*+210101,**>*2+00210`v
0 ^ 102210012+*1*<  ^<0210002<<
253

The last line isn't code; it's the input number.

Online interpreter: https://valthe.scheffers.net/testing/lolwhocares

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice first answer! Thanks for linking to an interpreter too! Lolwho.cares looks like an interesting fungeoid (if it is a fungeoid). \$\endgroup\$
    – user
    Commented Jun 5, 2021 at 23:40
  • \$\begingroup\$ I looked at the definition, it's probably a fungoid. \$\endgroup\$
    – Robot
    Commented Jun 6, 2021 at 10:03
2
\$\begingroup\$

JavaScript (ES6), 8 bytes

Beaten to the shortest solution (as usual!), so here's an alternative.

n=>n?n:1

Try It

f=
n=>n?n:1
console.log(f(0))
console.log(f(1))
console.log(f(8888))

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

PHP, 11 Bytes

<?=$argn?:1;

Online Version

\$\endgroup\$
2
\$\begingroup\$

Jelly, 2 bytes

o1

Try it online!

An alternative to the other Jelly solution. o provides a default value for a zero/empty argument; in this case, we default it to 1.

\$\endgroup\$
3
  • \$\begingroup\$ And another alternative is »1 \$\endgroup\$ Commented May 2, 2017 at 17:39
  • \$\begingroup\$ Now you're making me wonder if it's possible in 1 byte; I doubt it, but you have to wonder. The closest I've got is , which outputs the number itself for all nonzero numbers, and nothing if the input is 0. \$\endgroup\$
    – user62131
    Commented May 2, 2017 at 17:46
  • \$\begingroup\$ Yeah, another close one is m which yields [0,0] for 0 and n for n. \$\endgroup\$ Commented May 2, 2017 at 17:52
2
\$\begingroup\$

Binary-Encoded Golfical, 12 bytes

This binary encoding can be converted back to the standard graphical representation using the encoder provided in the Golfical github repo, or run directly using the interpreter by adding the -x flag.

Hexdump of binary encoding:

00 40 02 15 17 14 00 01 23 1D 17 14

Original image:

enter image description here

Magnified 120x, with color labels:

enter image description here

\$\endgroup\$
2
\$\begingroup\$

Whirl, 38 bytes

01100011100011110011111100001000111100

Try it online!

Explanation:

01100     op.ccw, op.intio    Mem1 = STDIN
011100    math.ccw, math.=    If (Mem1 = 0) Then (Math.Val = 1) Else (Math.Val = 0)
0111100   op.cw, op.one       Op.Val=1
11111100  math.add            Math.Val = Math.Val + Mem1
00        op.one              Op.Val=1 (Cheapest way to loop back to the Math wheel)
100       math.store          Mem1 = Math.Val
0111100   op.ccw, op.intio    STDOUT = Mem1
\$\endgroup\$
2
\$\begingroup\$

k, 2 bytes

1|

Finds the maximum of 1 and whatever number is given.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Perl 5, 10 +1 byte for -p flag = 11 bytes

$_=$_*1||1

Run with -p flag.

\$\endgroup\$
4
  • \$\begingroup\$ $_=$_||1 and thus $_||=1 is sufficient \$\endgroup\$
    – ikegami
    Commented May 3, 2017 at 16:51
  • \$\begingroup\$ Also, the other answers don't include the costs of outputting the result, so no need to count -p. \$\endgroup\$
    – ikegami
    Commented May 3, 2017 at 16:52
  • \$\begingroup\$ You are mistaken. Zero is false, whether stored as a number or as a string. However, if you populate $_ using echo 0 | perl -pe'...', you actually have "0\n", which is true. -l would take care of that. \$\endgroup\$
    – ikegami
    Commented May 3, 2017 at 17:30
  • 1
    \$\begingroup\$ @ikegami we consider here that requiring the input to be supplied without trailing newline is valid. (using echo -n ... for instance). Regarding the cost of outputting the result, the rules on PPCG say that the result need to be either printed, or returned by a function (which is what does the answer you linked), or returned some other way (I don't remember all valid options). (so counting -p flag is mandatory) \$\endgroup\$
    – Dada
    Commented May 4, 2017 at 12:23
2
\$\begingroup\$

GolfScript, 4 3* bytes

~1|

Try it Online!

*thanks to user a'_'

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Using a bitwise or would still work. \$\endgroup\$
    – user85052
    Commented Jan 26, 2020 at 11:22
2
\$\begingroup\$

Keg, -hr 4 bytes

:0=+

Try it online!

Explanation

:     # Take 2 inputs
  0=  # Check whether the input is 0
      # (Yields 1 if the input is 0)
      # (Yields 0 otherwise)
    + # Add the input with this result and print it rawly
      # i.e. 0->1, 5->5
\$\endgroup\$
2
  • \$\begingroup\$ 4 bytes: :0=+ \$\endgroup\$
    – lyxal
    Commented Dec 31, 2019 at 6:59
  • 1
    \$\begingroup\$ The "HighlyRadioactive" interpreter flag. \$\endgroup\$ Commented Aug 12, 2020 at 8:14
2
\$\begingroup\$

convey, 6 bytes

{+1
}.

Try it online!

Outputs the max of the input and 1. I think this is the optimal answer, since to use any binary function, there must be a second line with at least two characters.

You can also do the more traditional x+!x for 8 bytes.

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

Python 3, 16 bytes

lambda x:x+(x<1)

Try it online!

Thanks caird coinheringaahing for saving an extra byte!

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to CGCC. I think you can test for x<1 to save a byte: Try it online! \$\endgroup\$
    – Dingus
    Commented Jan 28, 2021 at 11:14
2
\$\begingroup\$

AWK, 8 bytes

$0||$0=1

Try it online!

Slightly different approach to this answer, reducing 2 bytes.

$0||$0=1      Basically, an OR logic gate. Right part is not considered if the left one is true.
              $0 is the input, parsed as true if different from zero, printing the input.
              If input is zero, $0 is set to 1 (right part).
              As $0 becomes 1, it is parsed true, and then the input is printed.
\$\endgroup\$
2
\$\begingroup\$

C (gcc), 11 bytes

f(n){n?:1;}

Try it online

\$\endgroup\$
2
  • \$\begingroup\$ I tried it online with the provided link, and it outputs 0, 6. \$\endgroup\$ Commented Dec 17, 2017 at 17:00
  • \$\begingroup\$ It seems they've changed the gcc behavior recently. If you switch to tcc it still works. \$\endgroup\$ Commented Jan 12, 2018 at 14:03
2
\$\begingroup\$

RegEx, 3 Bytes

Match pattern (2 Bytes):

^0

Substitution pattern (1 Byte):

1

Takes input as string without any leading zeros and substitutes it for 1 if it is 0.

Try on Regex101

\$\endgroup\$
2
\$\begingroup\$

Desmos, 10 bytes

Improvement suggested by Aiden Chow.

f(x)=0^x+x

Previous 13-byte solution:

f(x)=max(1,x)

Try it here

\$\endgroup\$
4
  • \$\begingroup\$ Desmos tips: you can have lists of integers like this. \$\endgroup\$
    – Leaky Nun
    Commented May 4, 2017 at 1:58
  • 1
    \$\begingroup\$ 10 bytes: f(x)=0^x+x. This works because 0^0 equals 1 in Desmos. \$\endgroup\$
    – Aiden Chow
    Commented Dec 30, 2023 at 8:15
  • \$\begingroup\$ @AidenChow That's wild. Thanks for letting me know! \$\endgroup\$
    – DanTheMan
    Commented Jan 4 at 19:38
  • 1
    \$\begingroup\$ Yea, this 0^x+x trick is actually used to avoid log(0) situations when trying to count the digits of a number. floor(logn)+1 (where n is the number we are trying to get the digits of) works if n is positive, but the shortest way to cover the n=0 case seems to be floor(log(0^n+n))+1. \$\endgroup\$
    – Aiden Chow
    Commented Jan 4 at 22:12

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.