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

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\$
2
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
  • 1
    \$\begingroup\$ Two bytes: |1 \$\endgroup\$
    – Zgarb
    Aug 5, 2017 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\$
1
  • \$\begingroup\$ |x:u64|x.max(1) \$\endgroup\$
    – alephalpha
    May 29, 2023 at 3:29
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\$

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
  • 1
    \$\begingroup\$ can it be a-(a<1)? \$\endgroup\$
    – l4m2
    Apr 12, 2018 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\$
1
  • \$\begingroup\$ @Makonede I'm afraid those don't work.. $~ and 1~ fail for even-numbered inputs (i.e. 4 results in 5; 6 results in 7; etc.) And the 1M will always result in 1, because it's the only value on the stack. \$\endgroup\$ Jan 28, 2021 at 20:59
0
\$\begingroup\$

Gaia, 2 bytes

1Ṁ

Try it online!

Takes the ax of 1 and the input.

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

MAWP, 4 20 bytes

%@_1A[1A~25WWM~]~?1:

Responds to numbers which have more than 1 digit.

Try it!

\$\endgroup\$
6
  • \$\begingroup\$ I tried the Keg solution, and it outputs nothing after 9. \$\endgroup\$
    – Razetime
    Aug 12, 2020 at 7:15
  • \$\begingroup\$ You were right. The Keg solution has now been fixed. \$\endgroup\$
    – Dingus
    Aug 12, 2020 at 7:40
  • \$\begingroup\$ @Razetime that's because it was trying to output it as a character. It needed a sneaky -hr interpreter flag. \$\endgroup\$
    – lyxal
    Aug 12, 2020 at 7:41
  • \$\begingroup\$ nice! Happy to help. \$\endgroup\$
    – Razetime
    Aug 12, 2020 at 7:42
  • \$\begingroup\$ Problem was that the poster (petStorm) had deleted that account long ago. So it needed someone else to fix it. \$\endgroup\$
    – lyxal
    Aug 12, 2020 at 7:43
0
\$\begingroup\$

Javascript, 8 11 bytes

Probably a bad implementation, but here:

n=>n==0?1:n

Explanation:

n // The input
n == 0 // Checks whether n is zero
?1 // If so, return 1.
:n // However, if n isn't zero, then return n
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Welcome to CGCC. Your approach works, but note that either a full program or function is required; hard-coded input is not allowed. Something like this would be acceptable. \$\endgroup\$
    – Dingus
    Jan 28, 2021 at 12:38
  • 1
    \$\begingroup\$ Thanks for the help, I've solved the problems, and rectified the things that need fixing! \$\endgroup\$
    – Rohan
    Jan 28, 2021 at 14:15
  • \$\begingroup\$ you can change n==0 to n<1 since input is non-negative for -1 byte \$\endgroup\$
    – MarcMush
    May 12, 2021 at 11:57
  • \$\begingroup\$ n||1 works fine \$\endgroup\$
    – emanresu A
    May 13, 2021 at 9:52
0
\$\begingroup\$

MMIX, 8 bytes (2 instrs)

(jxd)

00000000: 6300 0001 f801 0000                      c¡¡¢ẏ¢¡¡

(assembly)

foo CSZ $0,$0,1
    POP 1,0

Honestly, this function really should be inlined. It costs three instructions to call, but just one to inline.

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

Swift, 12 bytes

Types provided, 12 bytes

{$0==0?1:$0}
{
  $0 == 0 ? 1 : $0
}

Types not provided, 20 bytes

{(n:Int)in n==0?1:n}

```swift
{ (number: Int) -> Int in
  number == 0 ? 1 : number
}
\$\endgroup\$
1
0
\$\begingroup\$

C (clang), 63 42 bytes

main(i){scanf("%i",&i);printf("%i",i?:1);}

Try it online!

Much readable than C answers that already exists here. An if-else statement whether to output 1 or the other.

Thanks to ceilingcat for golfing 21 bytes.

\$\endgroup\$
3
  • 3
    \$\begingroup\$ If statement is an overkill for such task...... \$\endgroup\$
    – Wasif
    Jun 5, 2021 at 6:55
  • \$\begingroup\$ @Wasif It's pretty much the way for beginners. Using if statements always help with programs, and so here it is. Except ceilingcat has golfed it that it's not very visible. \$\endgroup\$ Jun 6, 2021 at 0:10
  • \$\begingroup\$ brevity/creativity is the target of code golf, readability be dammed, an if statement is sooooo boring, after the golf it looks much better, you might want to check Tips for golfing in C \$\endgroup\$
    – Wasif
    Jun 6, 2021 at 5:07
0
\$\begingroup\$

Thunno, \$ 2 \log_{256}(96) \approx \$ 1.65 bytes

1~

Attempt This Online!

Explanation: logical OR (~) with 1.

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