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 is0. - 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 code-golf, so shortest answer in bytes wins.
Standard loopholes apply.
-
1\$\begingroup\$ You should probably put a link to the TNB CMC, since that's where this challenge came from. \$\endgroup\$mbomb007– mbomb0072017年05月03日 20:53:52 +00:00Commented May 3, 2017 at 20:53
-
\$\begingroup\$ Does the answer need to be a full function, or can it be the body? \$\endgroup\$Caleb Kleveter– Caleb Kleveter2017年05月03日 20:58:40 +00:00Commented 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– Leaky Nun2017年05月04日 01:56:56 +00:00Commented May 4, 2017 at 1:56
-
\$\begingroup\$ Can we print the output with a leading zero? \$\endgroup\$MD XF– MD XF2017年12月26日 21:54:48 +00:00Commented Dec 26, 2017 at 21:54
-
1\$\begingroup\$ @LeakyNun the question text says "leading zeros are not allowed" but your comment contradicts this \$\endgroup\$Giuseppe– Giuseppe2018年01月17日 18:08:59 +00:00Commented Jan 17, 2018 at 18:08
170 Answers 170
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!
C, 17 bytes
f(n){return!n+n;}
C, 16 bytes
#define f(n)!n+n
-
\$\begingroup\$ tio.run/nexus/… hmmm... \$\endgroup\$betseg– betseg2017年05月02日 16:54:53 +00:00Commented May 2, 2017 at 16:54
-
1\$\begingroup\$ @betseg That's because it's a macro. The compiler sees it as
3*!n+nwhich equals3*0+5. \$\endgroup\$Steadybox– Steadybox2017年05月02日 16:56:41 +00:00Commented 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– betseg2017年05月02日 16:58:44 +00:00Commented 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– Steadybox2017年05月02日 17:00:07 +00:00Commented May 2, 2017 at 17:00
-
1\$\begingroup\$ @hucancode See the TIO links. You need to add a
mainfrom which the function/macrofis 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– Steadybox2017年05月03日 10:13:09 +00:00Commented May 3, 2017 at 10:13
JavaScript (ES6), 7 bytes
n=>n||1
-
7\$\begingroup\$ Alternative:
n=>n+!n(At least I think) \$\endgroup\$Matthew Roh– Matthew Roh2017年05月02日 16:45:00 +00:00Commented 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– Arnauld2017年05月02日 16:48:07 +00:00Commented May 2, 2017 at 16:48 -
\$\begingroup\$ this can be simplified to n||1. Only thing that evaluates to false is 0. \$\endgroup\$ansiart– ansiart2017年05月03日 22:42:57 +00:00Commented May 3, 2017 at 22:42
-
2\$\begingroup\$ @ansiart If your point is that
n=>n||1could be simplified ton||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– Arnauld2017年05月04日 01:40:34 +00:00Commented May 4, 2017 at 1:40 -
2\$\begingroup\$ @StanStrum We're required to return the original value of
nif it's not zero. A bitwise OR would modifynwhenever the least significant bit is not set (e.g.(4|1) === 5). \$\endgroup\$Arnauld– Arnauld2017年12月17日 23:26:39 +00:00Commented Dec 17, 2017 at 23:26
Japt, 2 bytes
a1
Explanation
a 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.
Haskell, 5 bytes
max 1
Usage example: (max 1) 0 -> 1.
Nothing much to explain.
Pyth, 2 bytes
+!
Explanation
+!
!Q 1 if (implicit) input is 0, 0 otherwise.
+ Q Add the (implicit) input.
Alice, 7 bytes
1/s
o@i
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.
V, 4 bytes
é0À
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
0is already a command (go the first column), andIn 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
-
1\$\begingroup\$ The one time that
0not being a count is useful. I didn't even consider it at first because I've avoided it so many times \$\endgroup\$nmjcman101– nmjcman1012017年05月02日 16:58:12 +00:00Commented May 2, 2017 at 16:58
Retina, 4 bytes
^0
1
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.)
dc, 7
?d0r^+p
Relies on the fact that dc evaluates 00 to 1, but 0n to 0 for all other n.
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.
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.
-
\$\begingroup\$ Another 13 bytes solution using
pryr:pryr::f(n+!n). Can't find anything smaller... \$\endgroup\$JayCe– JayCe2018年05月17日 02:51:20 +00:00Commented May 17, 2018 at 2:51
-
\$\begingroup\$ The paths to the Brainfuck compiler have changed, here is a fixed TIO demo \$\endgroup\$EasyasPi– EasyasPi2021年01月27日 19:50:04 +00:00Commented Jan 27, 2021 at 19:50
-
\$\begingroup\$ Alternatively
,[-<]>+.: Try it online! (It's worse because it goes out of bounds shortly.) \$\endgroup\$anderium– anderium2025年03月25日 23:39:53 +00:00Commented Mar 25 at 23:39
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 @.
V, 5 bytes
ç^0/<C-a>
Where <C-a> is 0x01.
Explanation
ç " On every line
^0/ " that begins with a zero do:
<C-a> " Increment the number on that line
-
1\$\begingroup\$ A little competition :) \$\endgroup\$DJMcMayhem– DJMcMayhem2017年05月02日 16:47:47 +00:00Commented May 2, 2017 at 16:47
R (削除) 20 (削除ここまで) 16 bytes
pryr::f(n+(n<1))
-
\$\begingroup\$ Welcome to PPCG! \$\endgroup\$Martin Ender– Martin Ender2017年06月14日 18:48:34 +00:00Commented Jun 14, 2017 at 18:48
-
\$\begingroup\$ Thanks @MartinEnder. I am already learn some tricks of the trade. \$\endgroup\$Shayne03– Shayne032017年06月15日 14:50:40 +00:00Commented Jun 15, 2017 at 14:50
Jelly, 2 bytes
+¬
Pretty much exactly my Pyth answer, but it's my first Jelly program.
Brachylog, 3 bytes
∅1|
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
Python, 15 bytes
lambda n:n or 1
-
\$\begingroup\$ Why not just
n or 1, 6 bytes? \$\endgroup\$DReispt– DReispt2017年05月04日 07:57:14 +00:00Commented 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– daniero2017年05月04日 10:47:09 +00:00Commented 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– daniero2017年05月04日 11:07:01 +00:00Commented May 4, 2017 at 11:07 -
3\$\begingroup\$ Alternative with the same 15-bytes byte-count:
lambda n:n|1>>n\$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2018年04月13日 09:24:13 +00:00Commented 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– ovs2021年06月05日 08:01:21 +00:00Commented Jun 5, 2021 at 8:01
Brain-Flak, (削除) 22 (削除ここまで), 10 bytes
({{}}[]{})
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)
-
\$\begingroup\$ Nice job, but not the shortest solution: codegolf.stackexchange.com/a/118520/31203 \$\endgroup\$MegaTom– MegaTom2017年05月02日 19:19:41 +00:00Commented May 2, 2017 at 19:19
TI-BASIC, 7 bytes
:Prompt X
:X+not(X
Alternatively,
TI-BASIC, 7 bytes
:Prompt X
:max(X,1
Hexagony, (削除) 7 (削除ここまで) 6 bytes
)?<@.!
Expanded:
) ?
< @ .
! .
Saved 1 byte thanks to Martin!
If the number is nonzero print it, otherwise add one to it and print that instead.
MarioLANG, 12 bytes
;
=[
:<+
=:
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.
Perl 5, 6 + 2 bytes for the -l and -p flags
$_||=1
Takes input on separate lines from stdin. Runs with the flags -lp.
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.
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
Excel, 10 Bytes
=A1+(A1=0)
This saves 4 Bytes over the obvious 'IF' statement solution, =IF(A1=0,1,A1).
-
3\$\begingroup\$ And 1 byte less than the less obvious
=A1+NOT(A1)\$\endgroup\$Engineer Toast– Engineer Toast2017年05月02日 20:05:27 +00:00Commented May 2, 2017 at 20:05
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
-
3\$\begingroup\$
i==0can be replaced byi<1\$\endgroup\$Leaky Nun– Leaky Nun2017年05月02日 16:58:43 +00:00Commented May 2, 2017 at 16:58
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!