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
    May 3, 2017 at 20:53
  • \$\begingroup\$ Does the answer need to be a full function, or can it be the body? \$\endgroup\$ 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
    May 4, 2017 at 1:56
  • \$\begingroup\$ Can we print the output with a leading zero? \$\endgroup\$
    – MD XF
    Dec 26, 2017 at 21:54
  • \$\begingroup\$ @MDXF yes, you can. \$\endgroup\$
    – Leaky Nun
    Dec 26, 2017 at 22:30

160 Answers 160

1
2 3 4 5 6
23
\$\begingroup\$

C (gcc), 14 13 bytes

f(n){n=n?:1;}

Thanks to @betseg for reminding me of the n?:1 trick in the comments of the other C answer!

Try it online!

C, 17 bytes

f(n){return!n+n;}

Try it online!

C, 16 bytes

#define f(n)!n+n

Try it online!

\$\endgroup\$
9
  • \$\begingroup\$ tio.run/nexus/… hmmm... \$\endgroup\$
    – betseg
    May 2, 2017 at 16:54
  • 1
    \$\begingroup\$ @betseg That's because it's a macro. The compiler sees it as 3*!n+n which equals 3*0+5. \$\endgroup\$
    – Steadybox
    May 2, 2017 at 16:56
  • 1
    \$\begingroup\$ I know, but I think you should be able to apply arithmetic operators to the "return" values directly, that's why it's common practice to put parentheses around macros. I just don't think that the macro is valid. \$\endgroup\$
    – betseg
    May 2, 2017 at 16:58
  • 5
    \$\begingroup\$ @betseg I don't think that's a requirement in code golf. I've never seen a code golf answer with C macros do that. \$\endgroup\$
    – Steadybox
    May 2, 2017 at 17:00
  • 1
    \$\begingroup\$ @hucancode See the TIO links. You need to add a main from which the function/macro f is called. A solution doesn't need to be a full program by default. The gcc-specific version may or may not compile on another compiler, and it may or may not run correctly when compiled on another compiler. \$\endgroup\$
    – Steadybox
    May 3, 2017 at 10:13
18
\$\begingroup\$

JavaScript (ES6), 7 bytes

n=>n||1
\$\endgroup\$
6
  • 7
    \$\begingroup\$ Alternative: n=>n+!n (At least I think) \$\endgroup\$ May 2, 2017 at 16:45
  • \$\begingroup\$ @SIGSEGV Yes, that would work indeed. (That could also be n|!n, although this one is limited to a 31-bit quantity.) \$\endgroup\$
    – Arnauld
    May 2, 2017 at 16:48
  • \$\begingroup\$ this can be simplified to n||1. Only thing that evaluates to false is 0. \$\endgroup\$
    – ansiart
    May 3, 2017 at 22:42
  • 2
    \$\begingroup\$ @ansiart If your point is that n=>n||1 could be simplified to n||1, then no. Acceptable answers are either full programs or functions. n=>do_something_with(n) is an arrow function in ES6 syntax. \$\endgroup\$
    – Arnauld
    May 4, 2017 at 1:40
  • 2
    \$\begingroup\$ @StanStrum We're required to return the original value of n if it's not zero. A bitwise OR would modify n whenever the least significant bit is not set (e.g. (4|1) === 5). \$\endgroup\$
    – Arnauld
    Dec 17, 2017 at 23:26
18
\$\begingroup\$

Japt, 2 bytes

ª1

Try it online!

Explanation

ª is a shortcut for JS's || operator. Japt has implicit input, so this program calculates input||1, and the result is implicitly sent to STDOUT.

w1 would work as well, taking the maximum of the input and 1.

\$\endgroup\$
18
\$\begingroup\$

Haskell, 5 bytes

max 1

Usage example: (max 1) 0 -> 1.

Nothing much to explain.

\$\endgroup\$
16
\$\begingroup\$

Pyth, 2 bytes

+!

Try it online

Explanation

+!
 !Q    1 if (implicit) input is 0, 0 otherwise.
+  Q   Add the (implicit) input.
\$\endgroup\$
15
\$\begingroup\$

Alice, 7 bytes

1/s
o@i

Try it online!

Explanation

1   Push 1. Irrelevant.
/   Reflect to SE. Switch to Ordinal.
i   Read all input as a string.
    Reflect off bottom right corner. Move back NW.
/   Reflect to W. Switch to Cardinal.
1   Push 1.
    IP wraps around to last column.
s   Sort swap: implicitly convert the input to an integer. Then, if the top stack 
    element is less than the one below, the two are swapped. It basically computes
    min and max of two values at the same time, with max on top.
/   Reflect to NW. Switch to Ordinal.
    Immediately reflect off the top boundary. Move SW.
o   Implicitly convert the result to a string and print it.
    Reflect off bottom left corner. Move back NE.
/   Reflect to S. Switch to Cardinal.
@   Terminate the program.
\$\endgroup\$
14
\$\begingroup\$

V, 4 bytes

é0À

Try it online!

Abuses an non-preferred but expected behavior, so I can't really call it a bug. Explanation:

In Vim, commands accept a count. For example, <C-a> will increment a number, but 7<C-a> will increment a number by 7. However, you can't use 0 as a count, because

  • 0 is already a command (go the first column), and

  • In the context of a text editor, it rarely makes sense to request that a command be run 0 times.

This is fine for a text editor, but usually obnoxious for a golfing language, so V overwrites some commands so that 0 is a valid count. For example, é, ñ, Ä, and some others. However, since <C-a> is a builtin vim command, it is not overwritten, so running this with a positive input gives:

N       " N times:
 <C-a>  "   Increment

But running with 0 as input gives:

0       " Go to column one
 <C-a>  " Increment

Full explanation:

é0          " Insert a 0
  À         " Arg1 or 1 times:
   <C-a>    " Increment
\$\endgroup\$
1
  • 1
    \$\begingroup\$ The one time that 0 not being a count is useful. I didn't even consider it at first because I've avoided it so many times \$\endgroup\$
    – nmjcman101
    May 2, 2017 at 16:58
13
\$\begingroup\$

J, 2 bytes

^*

Try it online!

^ [argument] raised to the power of

* the sign of the argument (0 if 0 else 1)

Because 1=0^0 in J.

\$\endgroup\$
11
\$\begingroup\$

Retina, 4 bytes

^0
1

Try it online!

If the input starts with a zero, replace that with a 1. (Works because the input is guaranteed to have no leading zeros for non-zero values.)

\$\endgroup\$
10
\$\begingroup\$

dc, 7

?d0r^+p

Relies on the fact that dc evaluates 00 to 1, but 0n to 0 for all other n.

Try it online.

\$\endgroup\$
10
\$\begingroup\$

brainfuck, 8 bytes

+>,[>]<.

Try it online!

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

R, 13 bytes

max(1,scan())

reads n from stdin. With pmax, it can read in a list and return the appropriate value for each element in the list for +1 byte.

try it online!

I should note that there is another fine R solution in 13 bytes by Sven Hohenstein which allows for yet another 13 byte solution of

(n=scan())+!n

which makes me wonder if that's the lower limit for R.

\$\endgroup\$
1
  • \$\begingroup\$ Another 13 bytes solution using pryr: pryr::f(n+!n). Can't find anything smaller... \$\endgroup\$
    – JayCe
    May 17, 2018 at 2:51
9
\$\begingroup\$

Cubix, 6 bytes

OI!1L@

Somehow managed to fit it on a unit cube... Test it online!

Explanation

Before being run, the code is arranged as a cube net:

  O
I ! 1 L
  @

The IP (instruction pointer) is then placed on the far-left face (I), facing to the right. The instructions run from there are:

I  Input a number from STDIN and push it to the stack.
!  If the top number is non-zero, skip the next instruction.
1  Push a 1 (only if the input was zero).
L  Turn left. The IP is now on the top face facing the !.
O  Output the top item as a number.

The IP then hits ! again, skipping the @ on the bottom face. This is not helpful, as we need to hit the @ to end the program. The IP hits the L again and goes through the middle line in reverse (L1!I) before ending up on the L one more time, which finally turns the IP onto @.

\$\endgroup\$
7
\$\begingroup\$

Oasis, 2 bytes

Uses the following formula: a(0) = 1, a(n) = n

n1

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice. My approach was >V. \$\endgroup\$
    – Leaky Nun
    May 2, 2017 at 16:43
  • \$\begingroup\$ @LeakyNun Oh nice! \$\endgroup\$
    – Adnan
    May 2, 2017 at 16:44
7
\$\begingroup\$

V, 5 bytes

ç^0/<C-a>

Where <C-a> is 0x01.

Try it online!

Explanation

ç                   " On every line
 ^0/                " that begins with a zero do:
    <C-a>           " Increment the number on that line
\$\endgroup\$
1
7
\$\begingroup\$

R 20 16 bytes

pryr::f(n+(n<1))
\$\endgroup\$
2
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Jun 14, 2017 at 18:48
  • \$\begingroup\$ Thanks @MartinEnder. I am already learn some tricks of the trade. \$\endgroup\$
    – Shayne03
    Jun 15, 2017 at 14:50
6
\$\begingroup\$

Jelly, 2 bytes

Try it online!

Pretty much exactly my Pyth answer, but it's my first Jelly program.

\$\endgroup\$
6
\$\begingroup\$

Brachylog, 3 bytes

∅1|

Try it online!

Explanation

If we add the implicit ? (Input) and . (Output), we have:

?∅          Input is empty (that is, [] or "" or 0 or 0.0)
  1.        Output = 1
    |       Else
     ?.     Input = Output
\$\endgroup\$
6
\$\begingroup\$

APL (Dyalog), 3 bytes

1∘⌈

Try it online!

This takes the ceil of the argument and 1.

\$\endgroup\$
6
\$\begingroup\$

Brain-Flak, 22, 10 bytes

({{}}[]{})

Try it online!

Explanation:

If the input is non-zero, then {{}} will pop everything off the stack and evaluate to the input. If it is zero, nothing will be popped, and it will evaluate to zero. So running ({{}}) gives

Non-zero:

n

Zero:

0
0

At this point, we'll add the height of the stack (0 for non-zero, 1 for zero) and pop one more value off the stack. (since the stack is padded with an infinite number of 0's, this will pop either the top 0 or an extra 0)

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

Hexagony, 7 6 bytes

)?<@.!

Expanded:

 ) ?
< @ .
 ! .

Try it online!

Saved 1 byte thanks to Martin!

If the number is nonzero print it, otherwise add one to it and print that instead.

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

Python, 15 bytes

lambda n:n or 1
\$\endgroup\$
5
  • \$\begingroup\$ Why not just n or 1, 6 bytes? \$\endgroup\$
    – DReispt
    May 4, 2017 at 7:57
  • 2
    \$\begingroup\$ Because that's just a snippet, while we usually answer with complete programs or functions. I'm not sure if this is stated explicitly in some rules somewhere, but at least that's the de facto standard. \$\endgroup\$
    – daniero
    May 4, 2017 at 10:47
  • \$\begingroup\$ Quoting trichoplax: The rules are not terribly clear. I think we have a consensus on meta that REPLs count, but as a separate language, which would allow snippets in many cases, but snippets are not permitted according to this meta post -> codegolf.meta.stackexchange.com/questions/2419/… \$\endgroup\$
    – daniero
    May 4, 2017 at 11:07
  • 3
    \$\begingroup\$ Alternative with the same 15-bytes byte-count: lambda n:n|1>>n \$\endgroup\$ Apr 13, 2018 at 9:24
  • \$\begingroup\$ One more notable 15 byter is lambda n:1-2%~n, other than that there are some variations of Kevin's function (n+0**n, 1>>n^n, ...) \$\endgroup\$
    – ovs
    Jun 5, 2021 at 8:01
5
\$\begingroup\$

MarioLANG, 12 bytes

;
=[
:<+
 =:

Try it online!

How it works

Mario starts in the top left, initially walking right. He reads an int from input (;) and stores it in the current memory cell. Then he falls off the ground (=), hitting [, which makes him ignore the next command if the current cell is 0.

If the cell is not 0, he'll start walking left (<), output the current cell as an int (:), and fall to his death (end of program).

If the cell is 0, he ignores the command to turn left, and keeps walking right. He increments the current cell (+), outputs it, and falls to his death.

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

TI-BASIC, 7 bytes

:Prompt X
:X+not(X

Alternatively,

TI-BASIC, 7 bytes

:Prompt X
:max(X,1
\$\endgroup\$
4
\$\begingroup\$

Mathematica, 9 8 bytes

Per Martin Ender:

#~Max~1&

First idea:

#/. 0->1&

Pure function with replaces 0 with 1. The space is necessary or it thinks we are dividing by .0.

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

dc, 11 bytes

[1]sf?d0=fp

[1]sf stores a macro in register f which pushes 1 to the top of the stack, ? reads input, d0=f runs macro f if input was 0, p prints the top of the stack.

Test:

$ dc -e "[1]sf?d0=fp" <<< 0
1
$ dc -e "[1]sf?d0=fp" <<< 1
1
$ dc -e "[1]sf?d0=fp" <<< 42
42
\$\endgroup\$
4
\$\begingroup\$

Excel, 10 Bytes

=A1+(A1=0)

This saves 4 Bytes over the obvious 'IF' statement solution, =IF(A1=0,1,A1).

\$\endgroup\$
1
  • 3
    \$\begingroup\$ And 1 byte less than the less obvious =A1+NOT(A1) \$\endgroup\$ May 2, 2017 at 20:05
4
\$\begingroup\$

Perl 5, 6 + 2 bytes for the -l and -p flags

$_||=1

Takes input on separate lines from stdin. Runs with the flags -lp.

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

Java 8, 10 bytes

i->i<1?1:i
  • Thanks to @LeakyNun for saving -1 byte
    • Didn't notice it's a non-negative integer
\$\endgroup\$
1
  • 3
    \$\begingroup\$ i==0 can be replaced by i<1 \$\endgroup\$
    – Leaky Nun
    May 2, 2017 at 16:58
4
\$\begingroup\$

Arnold C, 303 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 1
GET YOUR ASS TO MARS i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
BECAUSE I'M GOING TO SAY PLEASE i
TALK TO THE HAND i
BULLSHIT
TALK TO THE HAND 1
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED

Trying to explain it:

IT'S SHOWTIME //main()
HEY CHRISTMAS TREE i //int i
YOU SET US UP 1 //i = 1
GET YOUR ASS TO MARS i // ? compiler told me to add that
DO IT NOW // ? compiler told me to add that
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY // something related to reading from stdin
BECAUSE I'M GOING TO SAY PLEASE i // if(i)
TALK TO THE HAND i //print i
BULLSHIT //else
TALK TO THE HAND 1 //print 1
YOU HAVE NO RESPECT FOR LOGIC //endif
YOU HAVE BEEN TERMINATED //end main()

It even beats this answer!

\$\endgroup\$
1
2 3 4 5 6

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.