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

W, 2 bytes

1|

Explanation

a   # Take an input
 1| # Logical or with 1
    # If n is 0, this evaluates to 1
    # It evaluates to 0 otherwise
\$\endgroup\$
1
\$\begingroup\$

naz, 70 bytes

2a2x1v4a8m2x2v1x1f1r3x2v2e1o3f0x1x2f1a1o0x1x3f1r3x1v4e1o3f0x1x4f0a0x1f

Works for any input integer, provided it's passed as a file terminated with the control character STX (U+0002).

Explanation (with 0x commands removed)

2a2x1v           # Set variable 1 equal to 2
4a8m2x2v         # Set variable 2 equal to 48 ("0")
1x1f1r3x2v2e1o3f # Function 1
                 # Read a byte of input
                 # Jump to function 2 if it equals variable 2
                 # Otherwise, output it and jump to function 3
1x2f1a1o         # Function 2
                 # Add 1 to the register and output
1x3f1r3x1v4e1o3f # Function 3
                 # Read a byte of input
                 # Jump to function 4 if it equals variable 1
                 # Otherwise, output it and jump back to the start of function 3
1x4f0a           # Function 4
                 # Add 0 to the register
1f               # Call function 1
\$\endgroup\$
1
\$\begingroup\$

Flurry, 12 bytes

({})[(){}]{}

Run example

$ ./flurry -nin -c "({})[(){}]{}" 0
1
$ ./flurry -nin -c "({})[(){}]{}" 1
1
$ ./flurry -nin -c "({})[(){}]{}" 2
2
$ ./flurry -nin -c "({})[(){}]{}" 10
10

For single input n, computes n (K n) 1: apply "a constant function that returns n regardless of argument" n times to the number 1.

({})    Pop n and push n
[(){}]  Apply (K n); n is popped again from the stack
{}      Apply I (equivalent to number 1); popping from empty stack gives I

Reduction into SKI terms don't help much:

n (K n) 1
= I n (K n) 1
= S I K n 1
which translates into <>{{}}(){}{}
\$\endgroup\$
1
\$\begingroup\$

Rockstar, 24 bytes

listen to N
say N-0 or 1

Try it here (Code will need to be pasted in)

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

MathGolf, 2 bytes

┌+

Try it online.

Explanation:

┌   # Inverted boolean the (implicit) input-integer (1 if 0; 0 for any other integer)
 +  # Add this to the (implicit) input-integer
    # (after which the entire stack joined together is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

ARM Thumb-2 machine code, 6 bytes

Machine code:

b900 3001 4770

Assembly:

        .syntax unified
        .arch armv6t2
        .thumb
        .globl no_zero
        .thumb_func
no_zero:
        // skip next insn if r0 != 0
        cbnz    r0, .Ldont_add_1
.Ladd_1:
        // increment r0
        adds    r0, #1
.Ldont_add_1:
        // Return
        bx      lr

It doesn't get much simpler than that.

Input is in r0, output is in r0, follows standard calling convention.

ARM Thumb-2 machine code, branch/IT-less, 8 bytes

Only works for non-negative numbers unlike the branching solution.

Machine code:

4241 f140 0000 4770

Assembly:

        .syntax unified
        .arch armv6t2
        .thumb
        .globl no_zero_branchless
        .thumb_func
no_zero_branchless:
        // Negate r0 into r1. We only care about
        // setting the flags here.
        negs    r1, r0
        // Add the carry flag to r0. (wide insn)
        adc     r0, r0, #0
        // Return
        bx      lr

Follows the same calling convention.

negs follows the same rules as subs for setting flags. So, if r0 was positive, the result would have a borrow, but if it was 0, it would not.

Then, we just add with carry against zero to add 1 if r0 was zero, or 0 if r0 was positive.

Yes, you read that correctly.

When subtracting, ARM clears the carry flag to indicate a borrow. It is counterintuitive and usually annoying when golfing.

But I decided to use this for a small challenge.

Unfortunately, adc doesn't have a narrow immediate form, so we either have to waste another register to set it to zero, or use a wide instruction.

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

Sed, 7 bytes

Input in any number base, without any leading zeros. (It doesn't even need to be a consistent base!)

s/^0/1/

0 is the only number that begins with 0; just change that to 1.

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

Pxem, 12 bytes (content).

Unprintable characters are escaped.

.c\001.y.s\001.d.a

Usage

  • Expects stack has only an item, as an argument.
  • Stack content: (n, xxx) to (n', xxx, n, xxx).

Usage example

Filename to be _.e.n, with your input from stdin.

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

BRASCA, 14 7 bytes

ig:0=+n

Try it online

-7 bytes by RezNesX

Explanation

<implicit input> - Push STDIN to stack
ig               - Convert numbers from ASCII to number, and concatenate the stack
  :0=            - If the number is zero (pushes 1)
     +n          - Add and print as number.

```
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 7 bytes: ig:0=+n \$\endgroup\$
    – RezNesX
    May 12, 2021 at 11:39
1
\$\begingroup\$

Acc!!, 75 72 41 bytes

N
_+48/_
Count i while _/48 {
Write _
N
}

Try it online!

Explanation

N reads a character and stores its ASCII code into the accumulator.

Since the first character will always be a digit, the accumulator's value is between 48 and 57. If the accumulator is exactly 48, 48/_ will be 1; otherwise, it will be 0. We add this value to the accumulator. In effect: if the first digit of the number was 0, we consider it as 1; otherwise, we leave it unchanged.

We then enter a loop that writes the accumulator out as a character, reads another character into the accumulator, and loops until the ASCII code we read is less than 48 (probably 10 for newline). Then we halt.

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

Python 3, 19 bytes

lambda n:[n,1][n<1]

Try it online!

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

APOL, 8 bytes

¿(⧣ ⋔ 1)

Explanation

¿(   Returning if statement
  ⧣    Integer input (condition, 0 evaluates to false)
  ⋔    If item (returns the value of the condition, executed if true)
  1    A literal 1 (executed if false)
)
Implicit print
\$\endgroup\$
1
\$\begingroup\$

Vyxal, 3 bytes

¬[1

Try it Online!

Explanation:

# implict input
 ¬  # logical not
  [1  # 1 if truthy else the original input
# implict output
\$\endgroup\$
1
\$\begingroup\$

Aussie++, 60 bytes

THE HARD YAKKA FOR f IS(x)<YA RECKON x ==0?<BAIL 1;>BAIL x;>

All whitespace is mandatory. Tested in commit 9522366, where all numbers are truthy (see this issue), so I can't just say BAIL x ||1;.

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

Nekomata, 2 bytes

1M

Attempt This Online!

Max with 1.

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

Thunno 2, 2 bytes

1|

Attempt This Online! Logical OR with 1.

Alternative:

Attempt This Online! Maximum of input and 1.

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

Commodore BASIC (CBM/PET, VIC-20, Commodore C64, Commodore C16/+4) 19 BASIC tokens, 17 PETSCII characters with keyword abbreviations

0INPUTN:?N+-(N=.)

Very simple, in Commodore [early Microsoft] BASIC, if you do like PRINT X=Y it will return -1 if true, or 0 if false. A single equals is used for comparison and assignment, and the context is picked up by the interpreter.

We ask for a number with the INPUT keyword, which will enter a numeric value into the variable N. So we will then PRINT N plus a negative of the returned value of N=. with the . being a more performant replacement for 0 in this instance (a very trivial optimisation for such a short program). When N is 0, it adds --1, which just adds 1. When it is not zero, then we add -0 which is zero.

Stay Away from Zero on the CBM PET

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

R 4.1+, 8 bytes

\(n)n+!n

Attempt This Online!

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

BitCycle -u, 8 7 4 bytes

-1 byte thanks to Jo King

?/1!

Try it here!

How it works

The -u flag converts decimal inputs to unary and unary outputs to decimal. Inputs emerge from the source ? moving east.

  • For positive numbers, the splitter / sends one bit northward, off the playfield, while the other bits continue straight through. The 1 bit that started on the playfield, plus all but one of the input bits, land in the sink !, which therefore outputs the same number that was input (or more specifically, n-1+1).
  • For zero, there are no input bits, the splitter does nothing, and the 1 bit that started on the playfield lands in the sink and outputs 1.
\$\endgroup\$
0
0
\$\begingroup\$

CJam, 5 bytes

ri1e>

Try it online!

Explanation

ri   e# Read input as an integer
1    e# Push 1
e>   e# Maximum. Implictly display
\$\endgroup\$
0
\$\begingroup\$

Batch, 17 bytes

@cmd/cset/a%1+!%1
\$\endgroup\$
0
\$\begingroup\$

Math++, 3 bytes

?|1

("Body must be at least 30 characters")

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

Microscript II, 4 bytes

1sN|

Rough translation:

x=1
push x
x=readnum()
x|=pop()

x is then printed implicitly at the end.

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

braingasm, 4 bytes

;z+:

; reads a number from stdin, z+ increments that number if it is 0, : prints.

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

Ruby, 12 bytes

->n{n<1?1:n}

Try it online!


Alternate version that reads directly from STDIN instead of being a function. Same number of bytes after counting the -p flag (11+1 = 12 bytes). Effectively a port of the Retina solution.

sub /^0/,?1

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Nice, I wanted to post ->x{[x,1].max}, but your solution is 2 bytes shorter. \$\endgroup\$ May 3, 2017 at 10:10
0
\$\begingroup\$

Beam, 40 bytes

This reads the input as a string as it doesn't have any other option. Basically it checks if the first character is 0 by removing 48 from it. If 0 increment and output as a number, otherwise output it as a number, then read the rest of the input outputting it as characters.

 r'''''>`----\
 :+n++(------/
/<:<
r@
\u

Try it online!

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

Befunge-98, 5 bytes

&:!+.

Try it Online! (Warning - will take 60 seconds per test because of how TIO treats &)

Explanation

&:       Push 2 copies of the input
  !      Logical not the 1st copy - i.e. push 1 if 0, push 0 otherwise
   +     Add them together - this results in +0 normally, but +1 in the case of 0
    .    Print that value
         Loops back around to the first command
&        Because there's no more input, the TIO interpreter stalls for a minute and ends.

Befunge-93 Variant, 6 bytes

It's trivial to implement Befunge-93 in a similar way, except we can't use the & to end the program this time. Thus, the code is 1 byte longer, for 6 bytes:

&:!+.@

Try it Online!

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

CJam, 5 bytes

ri1e|

Explanation:

ri    e# Read token and convert to integer
  1e| e# OR with 0
\$\endgroup\$
2
  • \$\begingroup\$ | is bitwise OR, so an input of 2 will result in an output of 3. \$\endgroup\$
    – Dennis
    May 2, 2017 at 23:40
  • \$\begingroup\$ @Dennis That's true; edited. \$\endgroup\$ May 3, 2017 at 2:44
0
\$\begingroup\$

Clojure(Script), 10 bytes

#(max 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.