47
\$\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 '17 at 20:53
  • \$\begingroup\$ Does the answer need to be a full function, or can it be the body? \$\endgroup\$ 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

142 Answers 142

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

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

Python 3, 16 bytes

lambda x:x+(x<1)

Try it online!

Thanks caird coinheringaahing for saving an extra byte!

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to CGCC. I think you can test for x<1 to save a byte: Try it online! \$\endgroup\$
    – Dingus
    Jan 28 at 11:14
1
\$\begingroup\$

AWK, 8 bytes

$0||$0=1

Try it online!

Slightly different approach to this answer, reducing 2 bytes.

$0||$0=1      Basically, an OR logic gate. Right part is not considered if the left one is true.
              $0 is the input, parsed as true if different from zero, printing the input.
              If input is zero, $0 is set to 1 (right part).
              As $0 becomes 1, it is parsed true, and then the input is printed.
\$\endgroup\$
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 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\$
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 '17 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 '17 at 23:40
  • \$\begingroup\$ @Dennis That's true; edited. \$\endgroup\$ May 3 '17 at 2:44
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\$
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 '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\$

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.