Stay away from zero

42

3

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.

Leaky Nun

Posted 2017-05-02T16:28:41.980

Reputation: 45 011

1

You should probably put a link to the TNB CMC, since that's where this challenge came from.

– mbomb007 – 2017-05-03T20:53:52.313

Does the answer need to be a full function, or can it be the body? – Caleb Kleveter – 2017-05-03T20:58:40.040

1@CalebKleveter The default rule in PPCG is that the answer is either a function or a full program, but not snippets. – Leaky Nun – 2017-05-04T01:56:56.173

Can we print the output with a leading zero? – MD XF – 2017-12-26T21:54:48.247

@MDXF yes, you can. – Leaky Nun – 2017-12-26T22:30:39.573

@LeakyNun the question text says "leading zeros are not allowed" but your comment contradicts this – Giuseppe – 2018-01-17T18:08:59.110

Answers

18

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!

Try it online!

C, 17 bytes

f(n){return!n+n;}

Try it online!

C, 16 bytes

#define f(n)!n+n

Try it online!

Steadybox

Posted 2017-05-02T16:28:41.980

Reputation: 15 798

1@betseg That's because it's a macro. The compiler sees it as 3*!n+n which equals 3*0+5. – Steadybox – 2017-05-02T16:56:41.023

1I 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. – betseg – 2017-05-02T16:58:44.783

4@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. – Steadybox – 2017-05-02T17:00:07.087

I wonder how is this code can even be compiled. Please explain. – hucancode – 2017-05-03T10:08:36.603

1

@hucancode See the TIO links. You need to add a main from which the function/macro f is 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.

– Steadybox – 2017-05-03T10:13:09.123

@hucancode as for ?:, omitting middle term is allowed by some compilers. E.g. -std=gnu89 passed to GCC (which is its default mode) will compile this without errors. – Ruslan – 2017-05-03T15:23:48.890

Does f(n){n+=!n;}not work? – l4m2 – 2017-12-17T08:53:11.393

@l4m2 No, it doesn't. At least on TIO.

– Steadybox – 2017-12-17T13:27:30.510

17

Japt, 2 bytes

ª1

Try it online!

Explanation

ª 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.

ETHproductions

Posted 2017-05-02T16:28:41.980

Reputation: 47 880

16

Alice, 7 bytes

1/s
o@i

Try it online!

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.

Martin Ender

Posted 2017-05-02T16:28:41.980

Reputation: 184 808

15

Pyth, 2 bytes

+!

Try it online

Explanation

+!
 !Q    1 if (implicit) input is 0, 0 otherwise.
+  Q   Add the (implicit) input.

user48543

Posted 2017-05-02T16:28:41.980

Reputation:

15

JavaScript (ES6), 7 bytes

n=>n||1

Arnauld

Posted 2017-05-02T16:28:41.980

Reputation: 111 334

5Alternative: n=>n+!n (At least I think) – Matthew Roh – 2017-05-02T16:45:00.133

@SIGSEGV Yes, that would work indeed. (That could also be n|!n, although this one is limited to a 31-bit quantity.) – Arnauld – 2017-05-02T16:48:07.280

this can be simplified to n||1. Only thing that evaluates to false is 0. – ansiart – 2017-05-03T22:42:57.560

1

@ansiart If your point is that n=>n||1 could be simplified to n||1, then no. Acceptable answers are either full programs or functions. n=>do_something_with(n) is an arrow function in ES6 syntax.

– Arnauld – 2017-05-04T01:40:34.937

Why not n|1...? It makes sure the 1s place is always 1, making it not possible for it to be 0 – Stan Strum – 2017-12-17T23:21:45.270

1@StanStrum We're required to return the original value of n if it's not zero. A bitwise OR would modify n whenever the least significant bit is not set (e.g. (4|1) === 5). – Arnauld – 2017-12-17T23:26:39.653

13

Haskell, 5 bytes

max 1

Usage example: (max 1) 0 -> 1.

Nothing much to explain.

nimi

Posted 2017-05-02T16:28:41.980

Reputation: 34 639

12

Retina, 4 bytes

^0
1

Try it online!

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.)

Martin Ender

Posted 2017-05-02T16:28:41.980

Reputation: 184 808

12

V, 4 bytes

é0À

Try it online!

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

  • 0 is already a command (go the first column), and

  • In 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

James

Posted 2017-05-02T16:28:41.980

Reputation: 54 537

1The one time that 0 not being a count is useful. I didn't even consider it at first because I've avoided it so many times – nmjcman101 – 2017-05-02T16:58:12.147

12

J, 2 bytes

^*

Try it online!

^ [argument] raised to the power of

* the sign of the argument (0 if 0 else 1)

Because 1=0^0 in J.

Adám

Posted 2017-05-02T16:28:41.980

Reputation: 37 779

10

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.

try it online!

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.

Giuseppe

Posted 2017-05-02T16:28:41.980

Reputation: 21 077

Another 13 bytes solution using pryr: pryr::f(n+!n). Can't find anything smaller... – JayCe – 2018-05-17T02:51:20.683

10

dc, 7

?d0r^+p

Relies on the fact that dc evaluates 00 to 1, but 0n to 0 for all other n.

Try it online.

Digital Trauma

Posted 2017-05-02T16:28:41.980

Reputation: 64 644

9

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 @.

ETHproductions

Posted 2017-05-02T16:28:41.980

Reputation: 47 880

9

brainfuck, 8 bytes

+>,[>]<.

Try it online!

Dennis

Posted 2017-05-02T16:28:41.980

Reputation: 196 637

7

V, 5 bytes

ç^0/<C-a>

Where <C-a> is 0x01.

Try it online!

Explanation

ç                   " On every line
 ^0/                " that begins with a zero do:
    <C-a>           " Increment the number on that line

user41805

Posted 2017-05-02T16:28:41.980

Reputation: 16 320

1A little competition :) – James – 2017-05-02T16:47:47.453

6

Jelly, 2 bytes

Try it online!

Pretty much exactly my Pyth answer, but it's my first Jelly program.

user48543

Posted 2017-05-02T16:28:41.980

Reputation:

6

Oasis, 2 bytes

Uses the following formula: a(0) = 1, a(n) = n

n1

Try it online!

Adnan

Posted 2017-05-02T16:28:41.980

Reputation: 41 965

1Nice. My approach was >V. – Leaky Nun – 2017-05-02T16:43:52.790

@LeakyNun Oh nice! – Adnan – 2017-05-02T16:44:48.750

6

R 20 16 bytes

pryr::f(n+(n<1))

Shayne03

Posted 2017-05-02T16:28:41.980

Reputation: 347

Welcome to PPCG! – Martin Ender – 2017-06-14T18:48:34.197

Thanks @MartinEnder. I am already learn some tricks of the trade. – Shayne03 – 2017-06-15T14:50:40.303

5

Brain-Flak, 22, 10 bytes

({{}}[]{})

Try it online!

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)

James

Posted 2017-05-02T16:28:41.980

Reputation: 54 537

Nice job, but not the shortest solution: https://codegolf.stackexchange.com/a/118520/31203

– MegaTom – 2017-05-02T19:19:41.030

5

Brachylog, 3 bytes

∅1|

Try it online!

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

Fatalize

Posted 2017-05-02T16:28:41.980

Reputation: 32 976

5

MarioLANG, 12 bytes

;
=[
:<+
 =:

Try it online!

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.

Business Cat

Posted 2017-05-02T16:28:41.980

Reputation: 8 927

4

APL (Dyalog), 3 bytes

1∘⌈

Try it online!

This takes the ceil of the argument and 1.

user41805

Posted 2017-05-02T16:28:41.980

Reputation: 16 320

4

TI-BASIC, 7 bytes

:Prompt X
:X+not(X

Alternatively,

TI-BASIC, 7 bytes

:Prompt X
:max(X,1

Scott Milner

Posted 2017-05-02T16:28:41.980

Reputation: 1 806

4

Hexagony, 7 6 bytes

)?<@.!

Expanded:

 ) ?
< @ .
 ! .

Try it online!

Saved 1 byte thanks to Martin!

If the number is nonzero print it, otherwise add one to it and print that instead.

FryAmTheEggman

Posted 2017-05-02T16:28:41.980

Reputation: 16 206

4

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

Roman Gräf

Posted 2017-05-02T16:28:41.980

Reputation: 2 915

3i==0 can be replaced by i<1 – Leaky Nun – 2017-05-02T16:58:43.313

4

Python, 15 bytes

lambda n:n or 1

daniero

Posted 2017-05-02T16:28:41.980

Reputation: 17 193

Why not just n or 1, 6 bytes? – DReispt – 2017-05-04T07:57:14.707

2Because 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. – daniero – 2017-05-04T10:47:09.147

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 -> https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422

– daniero – 2017-05-04T11:07:01.310

@trichoplax 1or n would always return 1, wouldn't it? – daniero – 2017-05-04T11:08:51.453

Oh of course - sorry ignore me... – trichoplax – 2017-05-04T11:22:17.467

1

Alternative with the same 15-bytes byte-count: lambda n:n|1>>n

– Kevin Cruijssen – 2018-04-13T09:24:13.900

4

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

daniero

Posted 2017-05-02T16:28:41.980

Reputation: 17 193

4

Excel, 10 Bytes

=A1+(A1=0)

This saves 4 Bytes over the obvious 'IF' statement solution, =IF(A1=0,1,A1).

qoou

Posted 2017-05-02T16:28:41.980

Reputation: 711

3And 1 byte less than the less obvious =A1+NOT(A1) – Engineer Toast – 2017-05-02T20:05:27.700

4

R, 13 bytes

n=scan();n+!n

Here, scan is used to read the input value n. The negation of n (i.e., !n, 0 or 1) is added to n.

Sven Hohenstein

Posted 2017-05-02T16:28:41.980

Reputation: 2 464

3

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.

ngenisis

Posted 2017-05-02T16:28:41.980

Reputation: 4 600

3

Taxi, 517 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Knots Landing.Go to Knots Landing:n 2 r 2 r 1 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 1 l 2 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Formatted for humans:

Go to Post Office:w 1 l 1 r 1 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s 1 l 1 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:n 1 l 1 l 2 r.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Knots Landing.
Go to Knots Landing:n 2 r 2 r 1 l.
Pickup a passenger going to Addition Alley.
Go to Addition Alley:w 1 r 1 l 2 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:n 1 r 1 r.
Pickup a passenger going to Post Office.
Go to Post Office:n 1 l 1 r.

The key location is Knots Landing which performs the NOT operation so 0 returns 1 and all other numbers return 0. Now, you can go to Addition Alley to add the result from Knots Landing to the original input.

Engineer Toast

Posted 2017-05-02T16:28:41.980

Reputation: 5 769

3

Perl 5, 6 + 2 bytes for the -l and -p flags

$_||=1

Takes input on separate lines from stdin. Runs with the flags -lp.

Chris

Posted 2017-05-02T16:28:41.980

Reputation: 1 313

3

Braingolf, 8 bytes

!?_:1_;

Explanation:

 ?       If last element on stack > 0
!        Prevent if check from consuming last element on stack
  _      Pop last element on stack and print
   :     Else
    1    Add int literal 1 to end of stack
     _   Pop last element on stack and print
      ;  Prevent automatic pop of last element on stack

Skidsdev

Posted 2017-05-02T16:28:41.980

Reputation: 9 656

Is this your language? – Leaky Nun – 2017-05-03T14:55:07.243

1Yup, literally got bored at work today and decided to make a language. As you can tell it's very WIP, this is one of the only challenges that it can do beyond simply printing a string – Skidsdev – 2017-05-03T14:55:52.877

1Congratulations on your new language! – Leaky Nun – 2017-05-03T14:56:07.270

3

x86-64 Assembly, 10 9 bytes

Following the standard System V AMD64 calling convention, this function accepts a 32-bit unsigned integer parameter via the EDI register, and returns the result via the EAX register:

89 F8  |     mov   eax, edi    ; move parameter from EDI to EAX
85 C0  |     test  eax, eax    ; test input and set flags
75 01  |     jnz   Finished    ; if input is non-zero, then jump to end
FF 40  |     inc   eax         ; otherwise, input is 0, so increment it to 1
       |  Finished:
C3     |     ret               ; return, leaving result in EAX

x86-32 Assembly, 8 bytes

We could also write this as 32-bit code, since we're only dealing with 32-bit values.

The nice thing about this is that the INC instruction becomes only 1 byte in length. (In 32-bit mode, inc eax can be encoded simply as 40. In 64-bit mode, 40 is interpreted as a REX prefix, so the leading FF is needed. See Intel's documentation for this instruction.)

The caveat is that most 32-bit calling conventions pass parameters on the stack, rather than in registers, and loading a value from the stack (memory) takes many more bytes. If we can be allowed a __fastcall-style calling convention that passes parameters in registers (supported by virtually all C compilers, so not really cheating, just a bit less standard), then the integer parameter is passed in ECX and we get the following code, for a total of 8 bytes:

89 C8  |     mov  eax, ecx
85 C0  |     test eax, eax
75 01  |     jnz  Finished
40     |     inc  eax
       |  Finished:
C3     |     ret

Cody Gray

Posted 2017-05-02T16:28:41.980

Reputation: 2 639

Welcome to PPCG! – Justin – 2017-05-05T15:35:38.403

3

GCC command line, 9 bytes

-Df(x)x?:

Try it online!

-D in GCC checks if the following content has an =; if not, it add the code

#define <followed_content> 1

which in this case turns into

#define f(x)x?: 1

l4m2

Posted 2017-05-02T16:28:41.980

Reputation: 5 985

On meta I gave a common solution but here I give a pointed one – l4m2 – 2017-12-20T18:20:16.267

1Can the downvoter leave a comment? I find this very creative. – MD XF – 2017-12-26T21:36:43.310

3

Ruby, 11 bytes

->n{n|1>>n}

G B

Posted 2017-05-02T16:28:41.980

Reputation: 11 099

2

PHP, 11 Bytes

<?=$argn?:1;

Online Version

Jörg Hülsermann

Posted 2017-05-02T16:28:41.980

Reputation: 13 026

2

Binary-Encoded Golfical, 12 bytes

This binary encoding can be converted back to the standard graphical representation using the encoder provided in the Golfical github repo, or run directly using the interpreter by adding the -x flag.

Hexdump of binary encoding:

00 40 02 15 17 14 00 01 23 1D 17 14

Original image:

enter image description here

Magnified 120x, with color labels:

enter image description here

SuperJedi224

Posted 2017-05-02T16:28:41.980

Reputation: 11 342

2

Jelly, 2 bytes

o1

Try it online!

An alternative to the other Jelly solution. o provides a default value for a zero/empty argument; in this case, we default it to 1.

user62131

Posted 2017-05-02T16:28:41.980

Reputation:

And another alternative is »1 – Jonathan Allan – 2017-05-02T17:39:40.120

Now you're making me wonder if it's possible in 1 byte; I doubt it, but you have to wonder. The closest I've got is , which outputs the number itself for all nonzero numbers, and nothing if the input is 0. – None – 2017-05-02T17:46:00.087

Yeah, another close one is m which yields [0,0] for 0 and n for n. – Jonathan Allan – 2017-05-02T17:52:57.653

2

Perl 5, 10 +1 byte for -p flag = 11 bytes

$_=$_*1||1

Run with -p flag.

CraigR8806

Posted 2017-05-02T16:28:41.980

Reputation: 480

$_=$_||1 and thus $_||=1 is sufficient – ikegami – 2017-05-03T16:51:06.513

Also, the other answers don't include the costs of outputting the result, so no need to count -p.

– ikegami – 2017-05-03T16:52:16.560

You are mistaken. Zero is false, whether stored as a number or as a string. However, if you populate $_ using echo 0 | perl -pe'...', you actually have "0\n", which is true. -l would take care of that. – ikegami – 2017-05-03T17:30:36.963

1@ikegami we consider here that requiring the input to be supplied without trailing newline is valid. (using echo -n ... for instance). Regarding the cost of outputting the result, the rules on PPCG say that the result need to be either printed, or returned by a function (which is what does the answer you linked), or returned some other way (I don't remember all valid options). (so counting -p flag is mandatory) – Dada – 2017-05-04T12:23:29.470

2

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!

Skynet

Posted 2017-05-02T16:28:41.980

Reputation: 201

2

C (gcc), 11 bytes

f(n){n?:1;}

Try it online

Raycho Mukelov

Posted 2017-05-02T16:28:41.980

Reputation: 29

I tried it online with the provided link, and it outputs 0, 6. – Peter Taylor – 2017-12-17T17:00:51.817

It seems they've changed the gcc behavior recently. If you switch to tcc it still works. – Raycho Mukelov – 2018-01-12T14:03:26.380

2

x86 opcode, 6 5 bytes

       41                         INC     ECX
entry: E3 FD                      JECXZ   SHORT $-1
       91                         XCHG    EAX,ECX
       C3                         RETN

ECX -> EAX

l4m2

Posted 2017-05-02T16:28:41.980

Reputation: 5 985

You'll need to add a length in bytes, so other users can tell how long it is. Generally assembly or byte/op-code languages are measured in the size of the instructions the source represents. – Οurous – 2017-12-18T21:15:56.657

fixed. forgot. – l4m2 – 2017-12-18T21:26:15.737

2

Sinclair ZX81/Timex TS1000/1500 BASIC ~19 tokenized BASIC bytes

 1 INPUT A
 2 PRINT A+NOT A

This is a more efficient solution than the one below; essentially it takes the NOT value of A (which would be zero in all cases but zero) and adds that to the value of A.

Old answer:

Sinclair ZX81/Timex TS1000/1500 BASIC, ~31 tokenized BASIC bytes

 1 INPUT A
 2 IF NOT A THEN LET A=NOT A
 3 PRINT A

This takes a numeric input from the user and will display 1 if zero is entered by making A NOT A; otherwise it does nothing and displays the numeric value.

Shaun Bebbers

Posted 2017-05-02T16:28:41.980

Reputation: 1 814

2

Java 8, 9 bytes

n->n|1>>n

Try it online.

C# .NET, 9 bytes

n=>n|1>>n

Try it online.

Different approach (and 1 byte shorter) than the existing Java/C# .NET answers. (Also works with negative inputs.)

Explanation:

i->       // Method with integer as both parameter and return-type
  i|      //  Return the input bit-wise OR-ed with:
    1>>i  //  1 bit-wise right-shifted by the input

1>>i will be 1 when the input is 0, and 0 for every other input.
0|1 for input 0 will therefore result in 1, and n|0 for every other input will therefore result in n.

Kevin Cruijssen

Posted 2017-05-02T16:28:41.980

Reputation: 67 575

1See? You're getting better at bitwise operations ;-) – Olivier Grégoire – 2018-04-13T09:30:56.720

2

Keg, 4 bytes

:0=+

Try it online!

Explanation

¿:    # Take 2 inputs
  0=  # Check whether the input is 0
      # (Yields 1 if the input is 0)
      # (Yields 0 otherwise)
    + # Add the input with this result
      # i.e. 0->1, 5->5

user85052

Posted 2017-05-02T16:28:41.980

Reputation:

4 bytes: :0=+ – Lyxal – 2019-12-31T06:59:12.937

Oh, I forgot that now this works. – None – 2019-12-31T09:36:53.497

That works on TIO right now. – Lyxal – 2019-12-31T09:42:07.073

2

GolfScript, 4 3* bytes

~1|

Try it Online!

*thanks to user a'_'

LCU00

Posted 2017-05-02T16:28:41.980

Reputation: 31

1

Using a bitwise or would still work.

– None – 2020-01-26T11:22:32.103

2

Binary Lambda Calculus, 2.125 Bytes

00010110 00110001 0

Translation into lambda calculus:

\n. n (\x. n) (\x. x)

Itai Bar-Natan

Posted 2017-05-02T16:28:41.980

Reputation: 246

1

C, 27 Bytes

f(n){printf("%d\n",n?n:1);}

cleblanc

Posted 2017-05-02T16:28:41.980

Reputation: 3 360

You don't have to output, you can return that too. Also in GCC, you can do n?:1. – betseg – 2017-05-02T16:47:44.070

@betseg thanks I like that n?:1 trick – cleblanc – 2017-05-02T16:50:36.773

In this particular case you can also use n||1 which is compiler-independent, or !n+n as seen in several other answers. :) – fluffy – 2017-05-03T01:48:28.463

1

MATL, 3 bytes

t~+

Try it online!

Explanation

t   % Implicit inupt. Duplicate
~   % Logical negation. Converts zero to 1, and nonzero to 0
+   % Add. Implicit display

Luis Mendo

Posted 2017-05-02T16:28:41.980

Reputation: 87 464

1

JavaScript (ES6), 8 bytes

Beaten to the shortest solution (as usual!), so here's an alternative.

n=>n?n:1

Try It

f=
n=>n?n:1
console.log(f(0))
console.log(f(1))
console.log(f(8888))

Shaggy

Posted 2017-05-02T16:28:41.980

Reputation: 24 623

1

PowerShell, 24 22 17 Bytes

blatantly stolen from here

!($a=$args[0])+$a

Explanation

Invert the value, returning 0 for non-0 numbers, and 1 for 0, then add the intitial to it.

this makes it basically 1/0 + value, so for 0 the first value is 1, any other numbers it's 0.

examples:
# !0+0 = 1
# !1+1 = 1
# !9+9 = 9

colsw

Posted 2017-05-02T16:28:41.980

Reputation: 3 195

1

Could you instead use !$a as your index check? You wouldn't be able to set $a in your current manner, but I think something like this would work? Try it online!

– Sinusoid – 2017-05-02T21:13:43.723

1@Sinusoid that worked perfectly for -2, but turns out the C answer was a bit ahead of us both, didn't think of the method at all. – colsw – 2017-05-03T09:46:05.577

That is certainly interesting! I will need to keep this method in mind :P – Sinusoid – 2017-05-03T13:21:28.413

1

///, 11 bytes

/#0/1//#//#

Try it online!

Since there is no other way to take input in ///, hard-code the input after the last #.

Works by replacing #0 with 1. Then it removes any remaining #. The # makes sure that an input of 10 would not output 11.

Version that takes input in Itflabtijtslwi:

GGaGGGGbGG/#0/1//#//#ab

Try it online!

Comrade SparklePony

Posted 2017-05-02T16:28:41.980

Reputation: 5 784

For your second program, the input has to be less than 100. Maybe you should mention this? – boboquack – 2017-05-03T09:57:07.557

@boboquack Yes. – Comrade SparklePony – 2017-05-03T12:05:41.903

1

Ohm, 11 6 bytes

ö?┼¿1;

Uses CP-437 character encoding. Run with -c flag

Explanation:

ö?┼¿1;
       ■print(                                            )
  ┼    ■      first_input()
 ?   ; ■                   if(                     )
ö      ■                      int(first_input())!=0
   ¿   ■                                            else 
    1  ■                                                 1

Roman Gräf

Posted 2017-05-02T16:28:41.980

Reputation: 2 915

Here's a list of things you could fix: (1) if you just say this is in CP437 (no need for the -c flag), you only need to count characters. (2) Ohm is written in Ruby, so 0 is a truthy value. However, there is a built-in x != 0 component (ö). (3) There is implicit printing, so , is not necessary. (4) Ohm is on TIO now, so it'd help if you added a link to it.

– Nick Clifford – 2017-05-02T19:57:44.243

FYI, feel free to ping me in chat if you have any questions about/feature reqs for the language! – Nick Clifford – 2017-05-02T20:11:16.980

Again, there's no need for the -c flag. That's just for reading files; it's not necessary for PPCG submissions. Just say it's in CP437 and you're good. – Nick Clifford – 2017-05-02T20:36:48.667

1

AWK, 10 bytes

!$0{$0=1}1

Try it online!

Example Usage:

awk '!$0{$0=1}1' <<< 978

Robert Benson

Posted 2017-05-02T16:28:41.980

Reputation: 1 339

1

Clojure, 12 bytes

#(get[1]% %)

The get function takes an associative data structure, a key, and a default value. Vectors are associative using sequential position as the key. So, [1] is a vector with the value 1 at position 0. If get is called with parameter 0 it will return 1, otherwise no other keys exist in the vector so it returns the default value of the parameter.

mark

Posted 2017-05-02T16:28:41.980

Reputation: 251

1

Universal lambda, 3 bytes (17 bits)

00010110001100010

It is a function and not a complete program. I think it should work, but didn't actually test it because it doesn't seem easy to do so. It means λx.x(λy.x)(λy.y).

Lazy K, 10 bytes

S(SIK)(KI)

It is a function, untested, too.

jimmy23013

Posted 2017-05-02T16:28:41.980

Reputation: 34 042

1

05AB1E, 7 bytes

D0›i,}1

Try it online!

D           //push two inputs (implicit)
 0›         //push input greater than zero
   i        //if true
    ,}      //print input
      1     //push 1. printing is implicit if there is no previous output

osuka_

Posted 2017-05-02T16:28:41.980

Reputation: 391

I'm sure there is a much shorter way to do this... – Leaky Nun – 2017-05-02T18:56:14.893

Me too, but I can't actually work 05ab1e, so... – osuka_ – 2017-05-02T18:57:01.993

You could save 3 bytes with D_i1. – Emigna – 2017-05-02T20:25:00.320

3Or in two bytes: $M. – Adnan – 2017-05-02T21:51:01.273

1

Brain-Flak, 14 bytes

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

Try it online!

Just computes: 1 + (n ? n-1 : 0).

MegaTom

Posted 2017-05-02T16:28:41.980

Reputation: 3 787

Challenge accepted :) – James – 2017-05-03T21:08:42.317

1

Whirl, 38 bytes

01100011100011110011111100001000111100

Try it online!

Explanation:

01100     op.ccw, op.intio    Mem1 = STDIN
011100    math.ccw, math.=    If (Mem1 = 0) Then (Math.Val = 1) Else (Math.Val = 0)
0111100   op.cw, op.one       Op.Val=1
11111100  math.add            Math.Val = Math.Val + Mem1
00        op.one              Op.Val=1 (Cheapest way to loop back to the Math wheel)
100       math.store          Mem1 = Math.Val
0111100   op.ccw, op.intio    STDOUT = Mem1

Engineer Toast

Posted 2017-05-02T16:28:41.980

Reputation: 5 769

1

k, 2 bytes

1|

Finds the maximum of 1 and whatever number is given.

Try it online!

zgrep

Posted 2017-05-02T16:28:41.980

Reputation: 1 291

1

Java, 29 bytes

Try Online

int f(int n){return n<1?1:n;}

Khaled.K

Posted 2017-05-02T16:28:41.980

Reputation: 1 435

1

Starry, 14 bytes

, +'      +*`.

Try it online!

Explanation

Space shown as _ .

,           Read integer and push to stack
_+          Duplicate
'           If non-zero jump to branch label
______+     Push 1
*           Add
`           Mark branch label
.           Print as a number

Luis Mendo

Posted 2017-05-02T16:28:41.980

Reputation: 87 464

My first Starry answer – Luis Mendo – 2017-05-02T23:10:26.940

1

Japt, 2 bytes

w1

Try it online!

Returns the larger of 1 and the input.

Oliver

Posted 2017-05-02T16:28:41.980

Reputation: 7 160

1

C++, 22 bytes

[](int i){return!i+i;}

Try it online

Johan du Toit

Posted 2017-05-02T16:28:41.980

Reputation: 1 524

1

Excel, 10 bytes

=MAX(A1,1)

Here's another 10-byte solution: link

pajonk

Posted 2017-05-02T16:28:41.980

Reputation: 2 480

1

C#, 11 bytes

n=>n<1?1:n;

This compiles to a Func<int, int>.

TheLethalCoder

Posted 2017-05-02T16:28:41.980

Reputation: 6 930

1

SpecBAS - 20 bytes

1 INPUT n: ?n OR n=0

? is shorthand for PRINT

Brian

Posted 2017-05-02T16:28:41.980

Reputation: 1 209

1

Desmos, 13 bytes

f(x)=max(x,1)

Try it here

DanTheMan

Posted 2017-05-02T16:28:41.980

Reputation: 3 140

Desmos tips: you can have lists of integers like this.

– Leaky Nun – 2017-05-04T01:58:24.097

1

Clojure, 10 bytes

#(max 1%)

Not much to explain.

JoelSanchez

Posted 2017-05-02T16:28:41.980

Reputation: 11

I think you can shorten this to #(max 1%) (9 bytes). https://tio.run/nexus/clojure#0@DKSS1RiM7Lr0otyv@vrJGbWKFgqKr5P5ZLo6AoM68kJ09BAyKpYKCpiSloiE3QCCio@R8A

– Dennis – 2017-05-04T14:37:10.727

1

Chip, 20 18 bytes

eaABb
*`\\-!
fcCDd

Try it online!

How?

 aABb
            Copy the low 4 bits from input to output
 cCDd

e
*           Set the higher bits of output, so that the values are ASCII digits
f

eaABb
*           Replicate any ASCII digits on input to output
fcCDd

            -
     !      Produce a high signal, but only during the first byte
            -

 aAB
 `\\-*      Set the lowest bit of output, if the four low bits of input are unset
  CD

 aAB        Set the lowest bit of output, if the four low bits
 `\\-!      of input are unset, and only on the first byte
  CD

Phlarx

Posted 2017-05-02T16:28:41.980

Reputation: 1 366

1

Aceto, 9 8 bytes

rid0=`1p

read an integer and duplicate it, then push 0. Are they =? Then (`) push a 1. print the top element.

L3viathan

Posted 2017-05-02T16:28:41.980

Reputation: 3 151

1

Julia, 13 12 bytes

f(n)=n<1?1:n

Unfortunately, Julia doesn't do implicit casting from int to bool, so I have to burn an entire 3 characters just to do a comparison to zero. Saved one byte by safely assuming the number isn't negative. Still too verbose for my taste, though.

eaglgenes101

Posted 2017-05-02T16:28:41.980

Reputation: 577

You can post the answer as an anonymous function and save 2 bytes, n->n<1?1:n Try it online!

– sundar - Reinstate Monica – 2018-08-12T21:16:19.120

1

Python 21 Bytes

int(max('1',input()))

Takes input from REPL environment

tgabb

Posted 2017-05-02T16:28:41.980

Reputation: 11

1

Groovy, 7 bytes

{it?:1}

Elvis operator; if true, return self, else return 1. Only false integer value auto-unboxxed to false in Groovy is 0. Thusly, exactly the spec.

Magic Octopus Urn

Posted 2017-05-02T16:28:41.980

Reputation: 19 422

1

SNOBOL4 (CSNOBOL4), 49 47 36 bytes

	N =INPUT
	N =EQ(N) 1
	OUTPUT =N
END

Try it online!

Giuseppe

Posted 2017-05-02T16:28:41.980

Reputation: 21 077

1

Symbolic Python, 11 bytes

_+=_==(_>_)

Try it online!

_+=           # Output = Input +
   _==(_>_)                       Input == 0

FlipTack

Posted 2017-05-02T16:28:41.980

Reputation: 13 242

1

Google Sheets, 9 Bytes

Anonymous worksheet function that takes input from range A1 and outputs to the calling cell

=Max(1,A1

Taylor Scott

Posted 2017-05-02T16:28:41.980

Reputation: 6 709

This look very cool mate :) – NTCG – 2018-01-04T08:07:47.083

1

Bash, 43 bytes

if [ $1 -eq 0 ];then echo 1;else echo $1;fi

NTCG

Posted 2017-05-02T16:28:41.980

Reputation: 151

1

Julia 0.6, 10 bytes

x->x<1?1:x

Try it online!

gggg

Posted 2017-05-02T16:28:41.980

Reputation: 1 715

1also 10 bytes: x->x+(x<1) – Giuseppe – 2018-01-17T19:03:12.130

1

BitCycle, 8 7 bytes

-1 byte thanks to Jo King

?v<
!+~

Try it online!

Uses the -U flag to convert decimal inputs to "signed unary," which in this case means unary for positive integers and 0 for zero.

How it works

Let's run two example inputs: 3 and 0.

An input of 3 gets converted to 111 and emerges from the source (?) moving east. It follows the arrow down to the +, where the 1 bits turn right (west). They fall into the sink (!) and are converted back to decimal 3 and output.

An input of 0 gets converted to 0. When the 0 bit reaches the +, it turns left into the dupneg (~). Here the 0 turns right (south, off the playfield) and a negated copy of it turns left (north). This negated copy, being a 1 bit, goes back around to the + and turns right. It falls into the sink, is converted to decimal 1, and is output.

DLosc

Posted 2017-05-02T16:28:41.980

Reputation: 21 213

1

Acc!!, 75 72 bytes

N
Count i while 0^(_%12) {
Write 49
1
}
Count i while _/48 {
Write _
N
}

Try it online!

Explanation

The problem can be described as:

  • If the first character read is 0, output 1 and halt.
  • Otherwise, read a string of digits and echo them to output.

N reads a character and stores its code into the accumulator. The first loop triggers if the character read was 0 (i.e. ASCII 48):

  • If _ == 48, then (_%12) is 0, and 0^0 is 1, which is truthy.
  • If 49 <= _ <= 57, then (_%12) is between 1 and 9, and 0^(_%12) is 0, which is falsey.

Inside the first loop, we write a 1 (ASCII 49) and set the accumulator to 1. This breaks out of the loop because:

  • If _ == 1, then (_%12) is 1, and 0^1 is 0, which is falsey.

So when we reach the second loop, the accumulator is either 1 or some number between 49 and 57 (inclusive). The condition this time is _/48, which is truthy for values >= 48. So if the accumulator is 1 (meaning that we went into the first loop), we skip the second loop. Otherwise, we enter it. We write whatever's in the accumulator back to output and read another character, until the ASCII code we read is less than 48 (probably 10 for newline). Then we halt.

DLosc

Posted 2017-05-02T16:28:41.980

Reputation: 21 213

1

><>, 6 bytes

:?!1n;

Could have been 1 byte shorter if ? had the opposite conditional behaviour.

:?       check if nonzero, then either
  !      a) skip the next instruction or
   1     b) push 1 to the stack
    n    print
     ;   terminate

SE - stop firing the good guys

Posted 2017-05-02T16:28:41.980

Reputation: 529

Take the input via the -v flag instead. It saves a byte, and it's less suspect than using the char code of a character – Jo King – 2018-04-13T08:17:35.877

5 bytes – Jo King – 2018-04-13T10:34:39.790

Terminating with an error wasn't legal when I used to be around. – SE - stop firing the good guys – 2018-04-13T12:14:22.093

1

JavaScript (Node.js), 10 bytes

n=>n&&n||1

Try it online!

here is one more

JavaScript (Node.js), 8 bytes

n=>n?n:1

Try it online!

and lastly

JavaScript (Node.js), 7 bytes

n=>n||1

Try it online!

Muhammad Salman

Posted 2017-05-02T16:28:41.980

Reputation: 2 361

From the BASIC answer n=>n+!n (also 7 bytes) should also work ;) – Shieru Asakoto – 2019-09-06T05:39:48.807

1

Sed, 8 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.

Toby Speight

Posted 2017-05-02T16:28:41.980

Reputation: 5 058

1

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!

GammaFunction

Posted 2017-05-02T16:28:41.980

Reputation: 2 838

1

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

Reinstate Monica

Posted 2017-05-02T16:28:41.980

Reputation: 1 382

1

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

user85052

Posted 2017-05-02T16:28:41.980

Reputation:

1

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

sporeball

Posted 2017-05-02T16:28:41.980

Reputation: 461

0

CJam, 5 bytes

ri1e>

Try it online!

Explanation

ri   e# Read input as an integer
1    e# Push 1
e>   e# Maximum. Implictly display

Luis Mendo

Posted 2017-05-02T16:28:41.980

Reputation: 87 464

0

Batch, 17 bytes

@cmd/cset/a%1+!%1

Neil

Posted 2017-05-02T16:28:41.980

Reputation: 95 035

0

Math++, 3 bytes

?|1

("Body must be at least 30 characters")

SuperJedi224

Posted 2017-05-02T16:28:41.980

Reputation: 11 342

1https://chat.stackexchange.com/transcript/240?m=36422623#36422623 – Luis Mendo – 2017-05-02T23:20:49.023

0

Microscript II, 4 bytes

1sN|

Rough translation:

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

x is then printed implicitly at the end.

SuperJedi224

Posted 2017-05-02T16:28:41.980

Reputation: 11 342

0

braingasm, 4 bytes

;z+:

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

daniero

Posted 2017-05-02T16:28:41.980

Reputation: 17 193

0

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

steenbergh

Posted 2017-05-02T16:28:41.980

Reputation: 7 772

1can it be a-(a<1)? – l4m2 – 2018-04-12T08:08:25.030

0

CJam, 5 bytes

ri1e|

Explanation:

ri    e# Read token and convert to integer
  1e| e# OR with 0

Esolanging Fruit

Posted 2017-05-02T16:28:41.980

Reputation: 13 542

| is bitwise OR, so an input of 2 will result in an output of 3. – Dennis – 2017-05-02T23:40:44.673

@Dennis That's true; edited. – Esolanging Fruit – 2017-05-03T02:44:44.450

0

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!

Value Ink

Posted 2017-05-02T16:28:41.980

Reputation: 10 608

Nice, I wanted to post ->x{[x,1].max}, but your solution is 2 bytes shorter. – Eric Duminil – 2017-05-03T10:10:56.480

0

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!

sergiol

Posted 2017-05-02T16:28:41.980

Reputation: 3 055

0

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!

MickyT

Posted 2017-05-02T16:28:41.980

Reputation: 11 735

0

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!

MildlyMilquetoast

Posted 2017-05-02T16:28:41.980

Reputation: 2 907

0

Clojure(Script), 10 bytes

#(max 1 %)

madstap

Posted 2017-05-02T16:28:41.980

Reputation: 141

0

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.

quintopia

Posted 2017-05-02T16:28:41.980

Reputation: 3 899

0

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

Nurrl

Posted 2017-05-02T16:28:41.980

Reputation: 11

1I swear there's a golfier duplicate – Leaky Nun – 2017-05-03T06:52:09.810

Whoops :3 I'll search :D – Nurrl – 2017-05-03T13:33:52.913

0

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.

Caleb Kleveter

Posted 2017-05-02T16:28:41.980

Reputation: 647

0

Charcoal, 4 bytes

I∨N¹

Try it online!

Explanation

I    Cast (number is casted to string)
 ∨N¹ input number logical-or 1

ASCII-only

Posted 2017-05-02T16:28:41.980

Reputation: 4 687

0

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

Johannes

Posted 2017-05-02T16:28:41.980

Reputation: 1

0

Ruby, 13 bytes

->i{i==0?1:i}

dkudriavtsev

Posted 2017-05-02T16:28:41.980

Reputation: 5 781

0

JS ES5, 26 bytes

function (n){return n?n:1}

DN00B

Posted 2017-05-02T16:28:41.980

Reputation: 11

Save one byte by removing the space after function. – Zacharý – 2017-08-06T00:30:25.970

n||1 – l4m2 – 2017-12-18T20:42:57.933

I think you can also write this as function(n)n||1 (taking the n||1 idea from l4m2) – user41805 – 2018-01-05T15:15:52.907

0

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).

BradC

Posted 2017-05-02T16:28:41.980

Reputation: 6 099

0

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)]

Taylor Scott

Posted 2017-05-02T16:28:41.980

Reputation: 6 709

0

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!

ბიმო

Posted 2017-05-02T16:28:41.980

Reputation: 15 345

1Two bytes: |1 – Zgarb – 2017-08-05T08:14:58.123

0

,,,, 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.

totallyhuman

Posted 2017-05-02T16:28:41.980

Reputation: 15 378

0

Element, 8 bytes

_2:'!"+`

Try it online

aAaa aAaa

Posted 2017-05-02T16:28:41.980

Reputation: 141

0

Pushy, 4 bytes

&n+#

Try it online!

   #  \ print:
  +   \   input + ...
&n    \   not(input)

FlipTack

Posted 2017-05-02T16:28:41.980

Reputation: 13 242

0

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.

Håvard Nygård

Posted 2017-05-02T16:28:41.980

Reputation: 341

0

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

Jo King

Posted 2017-05-02T16:28:41.980

Reputation: 38 234

0

Implicit, 7 bytes

$!{.

Try it online! Explanation:

$      read input
 !{    if falsy
   .   increment
       implicit output

MD XF

Posted 2017-05-02T16:28:41.980

Reputation: 11 605

0

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.

Bolce Bussiere

Posted 2017-05-02T16:28:41.980

Reputation: 970

0

Clean, 9 bytes

?0=1
?n=n

Try it online!

Οurous

Posted 2017-05-02T16:28:41.980

Reputation: 7 916

0

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.

DLosc

Posted 2017-05-02T16:28:41.980

Reputation: 21 213

0

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).

Kevin Cruijssen

Posted 2017-05-02T16:28:41.980

Reputation: 67 575

0

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

Bubbler

Posted 2017-05-02T16:28:41.980

Reputation: 16 616

0

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)

Kevin Cruijssen

Posted 2017-05-02T16:28:41.980

Reputation: 67 575

0

Gaia, 2 bytes

1Ṁ

Try it online!

Takes the ax of 1 and the input.

Giuseppe

Posted 2017-05-02T16:28:41.980

Reputation: 21 077

-1

Excel VBA 17 bytes

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

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

Stupid_Intern

Posted 2017-05-02T16:28:41.980

Reputation: 373

1Hey, 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. – Taylor Scott – 2017-06-14T20:29:41.333

2Save two bytes and make it a valid answer with ?-([A1]=0)+[A1] – Engineer Toast – 2017-08-07T14:00:41.240