41
\$\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\$
  • 1
    \$\begingroup\$ You should probably put a link to the TNB CMC, since that's where this challenge came from. \$\endgroup\$ – mbomb007 May 3 '17 at 20:53
  • \$\begingroup\$ Does the answer need to be a full function, or can it be the body? \$\endgroup\$ – Caleb Kleveter May 3 '17 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 '17 at 1:56
  • \$\begingroup\$ Can we print the output with a leading zero? \$\endgroup\$ – MD XF Dec 26 '17 at 21:54
  • \$\begingroup\$ @MDXF yes, you can. \$\endgroup\$ – Leaky Nun Dec 26 '17 at 22:30

119 Answers 119

0
\$\begingroup\$

Clojure(Script), 10 bytes

#(max 1 %)
\$\endgroup\$
0
\$\begingroup\$

Silberjoder, 42 bytes


0+b1,-CB+b1:BC<. +iB-b1+CB-CA[+CA.,-CA]1

How it works:


0

The first three characters are all data and are not executed. They are a newline (10), a zero (48), and a DC3 (19).

+b1

Point b at the "0" character. Note that a is still pointing at the newline character.

,

Read the first character of input.

-CB

Subtract what b is pointing to (the "0") from the first digit.

+b1

Point b at the DC3 character, which has value 19

:BC

Jump to position 19+3=22 if the c is pointing to anything other than zero. This would happen if the first digit of the number was anything other than "0". Otherwise...

<.

Move c on top of the "1" at the end of the program and print it.

 +iB

b is still pointing at 19, so we add 19 to the instruction pointer, jumping to the "1" at the end of the program, causing the program to halt after one more cycle. (The extra space is ignored, but we need it there to position this instruction so that the instruction pointer jumps beyond the "]" at the end of the program. If we don't do this, we will enter the loop at the end, and print an extraneous semicolon whenever 0 is input.)

-b1

This is position 22, so we jump here whenever the number didn't start with "0". We move b back to point at the "0".

+CB

Add the 48 back to the first digit of the number, restoring it to its proper character value.

-CA

Subtract the newline from the digit.

[+CA.

If it's not zero, restore it to its original value and print it.

,-CA]

Repeat reading digits, comparing them with newline, and printing them until newline is seen.

1

Data. Ignored. Program halts.

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

JavaScript, 19 Bytes

(x)=>{return x?x:1}

Ungolefed, with example:

function f(n) {
  if(n)
    return n;
  else
    return 1;
}

f(0); // 1
f(1); // 1
f(2); // 2
\$\endgroup\$
0
\$\begingroup\$

Swift, 25 bytes

max(1, Int(readLine()!)!)

If you just have the body of a closure, then it is just 10 bytes:

max(1, $0)

Takes in standard input and then returns the max int, which would either be 1 or higher.

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

Charcoal, 4 bytes

I∨N¹

Try it online!

Explanation

I    Cast (number is casted to string)
 ∨N¹ input number logical-or 1
\$\endgroup\$
0
\$\begingroup\$

Groovy, 9 bytes

f={it?:1}

Inside a groovy script file you can run with "groovy -D n=0 ":

println System.properties.n?:1

As a closure:

f={it?:1}

1) "?:" is groovy's "elvis-operator"

One instance of where this is handy is for returning a 'sensible default' value if an expression resolves to false-ish

2) "it" refers to a single anonymous parameter the closure is called with

3) 0 evaluates to false in groovy-truth

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

Tcl, 25

puts [expr $argv?$argv:1]

demo — How to use: In the green area, type

tclsh main.tcl $n

where $n is the input number. Do not press backspace, otherwise your browser can go back in history!

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

Ruby, 13 bytes

->i{i==0?1:i}
\$\endgroup\$
0
\$\begingroup\$

T-SQL, 21 bytes

SELECT MAX(1,a)FROM t

SQL input is allowed via a pre-existing named table (table t with INT field a).

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

Husk, 3 2 bytes

|1

Try it online!

Ungolfed/Explanation

    -- implicit input N
|   -- if N is truthy: N
 1  -- else (N==0): 1

Thanks @Zgarb for -1 byte!

\$\endgroup\$
  • 1
    \$\begingroup\$ Two bytes: |1 \$\endgroup\$ – Zgarb Aug 5 '17 at 8:14
0
\$\begingroup\$

,,,, 2 bytes

1∨

Try it online!

,,, is on TIO now, so that's cool. Computes input or 1 (logical OR) and implicitly outputs the result.

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

Element, 8 bytes

_2:'!"+`

Try it online

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

Rust, 27 bytes

|x:u64|if x==0{1}else{x};

Anonymous function, or lambda, taking input from x.

First time golfing with Rust, and i must say im quite impressed.

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

Befunge, 6 Bytes

&:!+.@

Try it Online

& Gets input as number
  :! Duplicates and inverts
    +.@ Adds the inverted input to the original, prints and ends the program
\$\endgroup\$
0
\$\begingroup\$

Pushy, 4 bytes

&n+#

Try it online!

   #  \ print:
  +   \   input + ...
&n    \   not(input)
\$\endgroup\$
0
\$\begingroup\$

J, 6 Bytes

(>.1:)

Standard solution: Return the max of 1 and the argument.

The parenthesis ensure it's evaluated as a monadic hook:

(>.1:) 0
0 >. (1: 0)    NB. Definition of a monadic hook.
0 >. 1         NB. 1: is a constant function, always returns 1.
1              NB. >. returns the max of its two arguments.
\$\endgroup\$
0
\$\begingroup\$

Implicit, 7 bytes

$!{.

Try it online! Explanation:

$      read input
 !{    if falsy
   .   increment
       implicit output
\$\endgroup\$
0
\$\begingroup\$

Clean, 9 bytes

?0=1
?n=n

Try it online!

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

JS ES5, 26 bytes

function (n){return n?n:1}
\$\endgroup\$
  • \$\begingroup\$ Save one byte by removing the space after function. \$\endgroup\$ – Zacharý Aug 6 '17 at 0:30
  • \$\begingroup\$ n||1 \$\endgroup\$ – l4m2 Dec 18 '17 at 20:42
  • \$\begingroup\$ I think you can also write this as function(n)n||1 (taking the n||1 idea from l4m2) \$\endgroup\$ – Cows quack Jan 5 '18 at 15:15
0
\$\begingroup\$

Excel VBA, 17 13 Bytes

Anonymous VBE Immediate function that takes input as expected type unsigned integer and then outputs to the VBE immediate window

?[Max(A1,1)]

Previous Version

?[If(A1,A1,1)]
\$\endgroup\$
0
\$\begingroup\$

tinylisp, 14 bytes

(q((n)(i n n 1

This is a lambda function. In order to be able to call it, you either need to give it a name using d or call it directly (which would require explicitly closing the parentheses before specifying the argument). Try it online!

The function takes one argument, n. If n is truthy (all positive integers), return n. Otherwise (zero), return 1.

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

QBIC, 11 8 bytes

?:-(a>1)

Thanks to @l4m2 for saving me some bytes!

Explanation:

?         PRINT
 :        an integer taken from the cmd line (and store it as 'a')
  -       minus
   (a<1)  -1 if 'a' is less than 1 (can only be 0) or 0 otherwise.
          This leaves any a to be a, but turns zeroes into 1 by double negative.

Old code, that didn't use the inline : yet:

:?(a>0)+a+1

Explanation

:       Get an int from the cmd line, a
?       PRINT
 (a>0)    if a is greater than 0, this is -1, else 0
 +a        yields 0 for 0 and a-1 for >0
 +1        makes 1's for 0 and a's for all other values
\$\endgroup\$
  • 1
    \$\begingroup\$ can it be a-(a<1)? \$\endgroup\$ – l4m2 Apr 12 '18 at 8:08
0
\$\begingroup\$

Whitespace, 41 bytes

[S S S N
_Push_0][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input][N
T   S N
_If_0_jump_to_Label_0][T    N
S T _Print_as_integer][N
N
N
_Exit][N
S S N
_Create_Label_0][S S S T    N
_Push_1][T  N
S T Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Explanation in pseudo-code:

Integer i = STDIN as integer
If i == 0:
  Call function Label_0
Print i
Exit program

function Label_0:
  Print 1
  Exit implicitly with error: Exit not defined

Example runs:

Input: 0

Command    Explanation              Stack    Heap     STDIN    STDOUT    STDERR

SSSN       Push 0                   [0]
SNS        Duplicate top (0)        [0,0]
TNTT       Read STDIN as integer    [0]      {0:0}    0
TTT        Retrieve                 [0]      {0:0}
SNS        Duplicate top (0)        [0,0]    {0:0}
NTSN       If 0: Jump to Label_0    [0]      {0:0}
NSSN       Create Label_0           [0]      {0:0}
SSSTN      Push 1                   [0,1]    {0:0}
TNST       Print as integer         [0]      {0:0}             1
                                                                         error

Try it online (with raw spaces, tabs and new-lines only).
Stops with error: Exit not defined.

Example runs:

Input: 5

Command    Explanation              Stack    Heap     STDIN    STDOUT    STDERR

SSSN       Push 0                   [0]
SNS        Duplicate top (0)        [0,0]
TNTT       Read STDIN as integer    [0]      {0:5}    5
TTT        Retrieve                 [5]      {0:5}
SNS        Duplicate top (5)        [5,5]    {0:5}
NTSN       If 0: Jump to Label_0    [5]      {0:5}
TNST       Print as integer         []       {0:5}             5
NNN        Exit program             []       {0:5}

Try it online (with raw spaces, tabs and new-lines only).

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

Gol><>, 5 bytes

I:z+h

Try it online!

Given n, calculate n + !n, print as int and halt. Unfortunately Gol><> doesn't have implicit input option, so the bytes are the same as regular ><>.

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

05AB1E, 2 bytes

_+

Try it online or verify some more test cases.

2 bytes alternative by @Adnan:

$M

Try it online or verify some more test cases.

Explanation:

_   # Check if the (implicit) input is 0 (0 becomes 1; everything else becomes 0)
 +  # Add it to the (implicit) input (0 becomes 1; everything else stays the same)
    # (and output the result implicitly)

$   # Push both 1 and the input to the stack
 M  # Push the largest number of the stack (without changing the rest of the stack)
    # (and output the top of the stack implicitly as result)
\$\endgroup\$
0
\$\begingroup\$

Gaia, 2 bytes

1Ṁ

Try it online!

Takes the ax of 1 and the input.

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

Triangular, 6 bytes

$,w%1<

Try it online!

Ungolfed:

  $
 , w
% 1 <
-----------------------
$              Read from input as an integer
 w,            Change directions if ToS != 0 (will go straight to print)
   <1          Push 1
     %         Print ToS as an integer
\$\endgroup\$
-1
\$\begingroup\$

Excel VBA 17 bytes

[a1]=IIF(n=0,1,n)

Simple if else statement you can run it from vba immediate window

\$\endgroup\$
  • 1
    \$\begingroup\$ Hey, just a note on convention with VBA and Excel VBA for PPCG - you must take input from either a cell or from a passed variable. You can output to the immediate window, msgbox, function value, to a cell or by modifying a passed variable. This means that your above solution is not valid as it does not take input from cell or a passed variable, but rather relies on the variable being passed to it. \$\endgroup\$ – Taylor Scott Jun 14 '17 at 20:29
  • 2
    \$\begingroup\$ Save two bytes and make it a valid answer with ?-([A1]=0)+[A1] \$\endgroup\$ – Engineer Toast Aug 7 '17 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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