66
\$\begingroup\$

Given a number N, output the sign of N:

  • If N is positive, output 1
  • If N is negative, output -1
  • If N is 0, output 0

N will be an integer within the representable range of integers in your chosen language.

\$\endgroup\$
  • 45
    \$\begingroup\$ This is a trivial challenge with a lot of trivial solutions. There are however some non-trivial solutions too. To voters: Please read the first sentence of this meta post before upvoting builtin functions. \$\endgroup\$ – Stewie Griffin Dec 20 '16 at 10:10
  • 8
    \$\begingroup\$ This could probably use a leaderboard. \$\endgroup\$ – Martin Ender Dec 20 '16 at 11:13
  • 2
    \$\begingroup\$ @MrLister upvote how you want, but really you should look for creativity instead of code length. \$\endgroup\$ – FlipTack Dec 28 '16 at 20:13
  • 3
    \$\begingroup\$ @FlipTack Oh, I thought it was codegolf. \$\endgroup\$ – Mr Lister Dec 28 '16 at 20:23
  • 3
    \$\begingroup\$ @MrLister that's the objective winning criterion. but does it really take more effort to type s for a sign builtin, or use some clever bitshifting/maths to work it out? Have a look at this meta post \$\endgroup\$ – FlipTack Dec 28 '16 at 20:25

141 Answers 141

2
\$\begingroup\$

Triangular, 26 15 bytes

$\:-|0U%<g/l0P<

Formats into this triangle:

     $ 
    \ : 
   - | 0 
  U % < g 
 / l 0 P < 

Try it online!


Old broken version that I understand:

$\:-%0U..g/l0P<

Try it online! Currently nonworking until Dennis pulls; found some interpreter bugs.

Formats into this triangle:

    $
   \ :
  - % 0
 U . . g
/ l 0 P <

How it works: The code, without directionals, is read as $:0gP0lU-%.

  • $ reads an integer from standard input.
    stack: i
  • : duplicates the top stack value.
    stack: i,i
  • 0 pushes 0 to the stack.
    stack: i,i,0
  • g pushes i>0 to the stack and discards both values used (thanks, Luis Mendo).
    stack: i,i>0
  • P pops the top stack value into the register.
    stack: i
  • 0 pushes 0 to the stack.
    stack: i,0
  • l pushes i<0 to the stack and discards the values used.
    stack: i<0
  • U pulls the register onto the stack.
    stack: i<0,i>0
  • - computes a postfix subtract.
    stack: i<0-i>0
  • % prints the top stack value as an integer.

Idea thanks to caird.

\$\endgroup\$
  • \$\begingroup\$ This fails, by outputting the inverse sign. However, this is correct, and is the same length. \$\endgroup\$ – caird coinheringaahing Oct 31 '17 at 18:42
2
\$\begingroup\$

Befunge-93 (PyFunge), 12 bytes

~"1"%90p1X.@

Try it online!

Note that the X can be anything (except a new line), as it gets written over during run-time. It's just easier for explanation

Similar to my other Befunge answer, but this time it mods the first character by the ASCII for 1 first, so that a positive first digit will turn into a no-op, leaving the 1 on the top of the stack:

~               Read the first *character* of input - either a digit or "-"
 "1"%           Mod the character by the ASCII value of 1. After this step, the character
                is a '-' for negative numbers, '0' for 0, and small, unprintable
                characters for positive numbers

     90p        Puts the character in the space with the X.
        1       Pushes a 1

         X      3 different options based on the character that was put here:
         -      Negative: Subtract the 1 from the implicit 0 to get -1
         0      Zero:     Push 0
               Positive: A no-op, which leaves the 1 on top

          .     Prints out the top of the stack
           @    Ends the program
\$\endgroup\$
2
\$\begingroup\$

Minecraft Functions (18w11a, 1.13 snapshots), 131 bytes

Number signs in minecraft

Uses a function named a in the minecraft namespace

execute if score @p n matches 0 run say 0
execute if score @p n matches 1.. run say 1
execute if score @p n matches ..-1 run say -1

"Takes input" from a scoreboard objective named n, create it with /scoreboard objectives add n dummy and then set it using /scoreboard players set @p n 8. Then call the function using /function a

\$\endgroup\$
2
\$\begingroup\$

Hexagony, 16 bytes

...!/~.?.<.!1@.,

Try it online!

Not much smaller than the previous answer, but strangely elegant in comparison.

Expanded:

   . . .
  ! / ~ .
 ? . < . !
  1 @ . ,
   . . .
\$\endgroup\$
1
\$\begingroup\$

Japt, 2 bytes

Ug

Test it online!

U is the input number, and g is the sign function on numbers. Output is implicit.

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

Pyth, 2 bytes

._

herokuapp

Pyth's sign function.

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

Matlab, 4 bytes

sign

Matlab as well has a builtin for it.

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

Octave, 4 bytes

As with many others, a built-in:

sign

Please, read the first sentence of this meta post before voting.

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

WolframAlpha, 3 bytes

Try it online: sgn

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

PowerShell, 22 bytes

[math]::sign($args[0])

Boring built-in, calls the .NET function that does exactly what it says on the tin. Ho-hum.
Try it online!


For 26 bytes however, we get the classic greater-than less-than equation

param($b)($b-gt0)-($b-lt0)

This, at least, has a little bit of logic and thought put into it. Try it online!


Best yet, though is 44 bytes, where we roll our own solution.

param($b)if("$b".indexof('-')){+!!$b;exit}-1

Here we take input $b, stringify it, take the .IndexOf('-') on it, and use it in an if clause. If the negative sign isn't found, this returns -1, which is truthy in PowerShell, so we turn $b into a Boolean with !, invert the Boolean with another !, cast it as an int with +, leave it on the pipeline, and exit. This turns a positive integer (which is truthy) into $false, then $true, then 1, while turning 0 into $true, then $false, then 0. Otherwise, the .IndexOf returned 0 (meaning it was the first character in the string), which is falsey, so we skip the if and just place a -1 on the pipeline. In either case, output via implicit Write-Output happens at program completion. Try it online!

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

Befunge, 11 bytes

&:0`\0\`-.@

Try it online!

This is just the obvious (N > 0) - (0 < N) calculation.

&               Read N from stdin.
 :              Make a duplicate copy.
  0`            Calculate N > 0.
    \           Swap the second copy to the top of the stack.
     0\`        Calculate 0 > N.
        -       Subtract the two comparisons: (N > 0) - (0 < N)
         .@     Output the result and exit.

As Martin Ender pointed out, there's potentially a 2-byte shorter solution, using the same idea as his ><> answer:

1~"/"-%.@

Unfortunately this only works if the result of a modulo operation takes the sign of the divisor, which is not that common in Befunge implementations (in particular the reference interpreter doesn't work this way).

1               Push 1 onto the stack for later use.
 ~              Read a character of input (this will be '-' or an ASCII digit).
  "/"-          Subtract 47.
      %         Take the modulo of the 1 we pushed earlier with this difference.
       .@       Output the result and exit.

If you want to try this out you'll probably need to use one of the Python-based interpreters like PyFunge or Befungee. I suspect Fungi might work too.

\$\endgroup\$
  • \$\begingroup\$ I think the arithmetic solution I used for my ><> answer and one of my Labyrinth answers would be 2 bytes shorter. \$\endgroup\$ – Martin Ender Dec 20 '16 at 13:46
  • \$\begingroup\$ If you use that approach you can save another byte with Befunge-98 which supports '/ for "/". (Provided any 98 interpreters exist with the correct modulo.) \$\endgroup\$ – Martin Ender Dec 20 '16 at 14:54
1
\$\begingroup\$

SAS Macro Language, 43 bytes

In the extremely wordy language...

%macro s(n);%put(%sysfunc(sign(&n)));%mend;
\$\endgroup\$
1
\$\begingroup\$

Jellyfish, 3 or 6 bytes

3 bytes with built-in:

p*i

Print (p) the sign (*) of the input (i). Automatically threads over lists.

6 bytes without built-ins:

p%S
 +i

Print (p) the division (%) of the input (i, taken from south with S) by the absolute value (+) of the input. Conveniently, division by 0 yields 0 in Jellyfish. This version also threads over lists. Try it online!

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

Clojure, 23 bytes

#(condp > % 0 -1 1 0 1)

This condp macro expands to "if less than 0 return -1, if less than 1 return 0 else 1".

(macroexpand '(condp > % 0 -1 1 0 1))
(let* [pred__7749 > expr__7750 %] (if (pred__7749 0 expr__7750) -1 (if (pred__7749 1 expr__7750) 0 1)))
\$\endgroup\$
1
\$\begingroup\$

PHP, 39 38 bytes

no comparison operators

<?=($n=$argv[1])&PHP_INT_MIN?-1:1-!$n;

should work on most systems.

PHP_INT_MIN has only one bit set: the most significant one. If this is set in the input, it is negative.
!$n (cast to integer by the subtraction) evaluates to 0 for positive values and 1 for 0.

lame solution, 30 bytes

<?=($n=$argv[1])?abs($n)/$n:0;

works also on floats.

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

Python 2, 57 bytes but no conditionals or comparitors

Just to be different, here's a solution that avoids all those ugly arithmetic functions:

def s(n):
 try:r=len([1][:n])*2-n/n
 except:r=0
 return r

Slicing a non-empty sequence [1][:n] returns [1] when n is positive and [] when negative or zero, so to distinguish these cases, n/n throws a divide by zero error for n=0.

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

QBIC, 18 8 bytes

:?sgn(a)

This utilizes Qbasic's SGN() function. : gets the input in variable a, ? prints.


Original version, before I learnt that QBasic has a SGN() function:

:~a=b|?a\?a/abs(a)

18 bytes. Explanation

:           Get 'a' from the command line
~a=b        If a == b (and b==0 by default)
|?a         Then print a
\?a/abs(a)  Else, print a / abs(a) --> -2/2 leaves the req. -1, 4/4 = 1
\$\endgroup\$
1
\$\begingroup\$

Javascript, 37 bytes

function s(n){return n>0?1:n<0?-1:0}
\$\endgroup\$
  • \$\begingroup\$ Sorry, updated! \$\endgroup\$ – Ostbullen Dec 21 '16 at 15:35
  • 2
    \$\begingroup\$ You could use a lambda: n=>n>0?1:n<0?-1:0 \$\endgroup\$ – Mego Dec 23 '16 at 14:45
1
\$\begingroup\$

awk, 17 bytes

!$0||$0=$0<0?-1:1

Test it:

$ echo 0 | awk '!$0||$0=$0<0?-1:1'
0
$ echo 2 | awk '!$0||$0=$0<0?-1:1'
1
$ echo -2 | awk '!$0||$0=$0<0?-1:1'
-1
\$\endgroup\$
1
\$\begingroup\$

MarioLANG, 868 bytes

;                                                    
=
  [@:
 =======================================================
                                                 ))    <
 ======================================================"
@ ((((++
=======            <
        ==========="
      @ -)+)+)+((([!))+((
      =============#====    (<
                         ===="
                       @ +)-[!)))
                       ======#==      )  <
                                 ========"
                                      >([!) 
                                      "==#        ))  <
                               @ -(-)[!+   ==========="
                               =======#:          >(([!!
                                                  "===##
                                         @ +((-))[!-
                                         =========#:

Ungolfed, with comments

;[>                                                        
==                                                                                                   output zero
    [@                                                                                            :                                                                      * start
  ==================================================================================================                  memory: [limit|limit_copy|counter_add|counter_sub|arg]
                                                    move pointer back to arg  ))    <
  =================================================================================="===
       increase counter limit
@   ((((++
=================    set counters
                              <
                  ============"     increase counter_add by one
                @ -)+)+)+ ((([! ))+((
                ==============#======
                                        reset limit
                                            (<
                                      ======="
                                    @ +)-   [! )))
                                    =========#====   try subtraction
                                                           )  <
                                                   ==========="
                                                         > ( [! ) 
                                                         "====#==
                                                 @ -(-) [!               try addition
                                                 ========#                   ))  <
                                                                  ==============="
                                                                           > (( [!  !
                                                                           "=====#==#
                                                                @  +((-)) [!
                                                                ===========#



                                                             output one       output minus one
                                                           +:                -:
                                                          ===               ===

What's going on?

The program maintains 5 memory fields (right to left):

  • Input value, continuously edited in search of zero
  • Counter for search in negative direction (subtraction)
  • Counter for search in positive direction (addition)
  • Helper to reset search radius (limit)
  • Current search interval radius (limit, k)

The algorithm keeps on searching for zero in both (+ and -) directions, starting at the input value. It does k negative and k+1 positive steps on each iteration, then increases k by 2. Once zero has been found, 1 or -1 is output, depending from which side it was reached.

Detection of zero as input is a special case, handled right at the beginning.

Try it online (commented, ungolfed version)

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

Python 3, 13 bytes

n//abs(n-.1)
\$\endgroup\$
  • 7
    \$\begingroup\$ Welcome to the site, and nice first answer! Just so you know, this is only a REPL snippet, which aren't a default valid form of output. You could wrap this in a lambda to make a function submission though. lambda n:n//abs(n-.1) \$\endgroup\$ – DJMcMayhem Dec 24 '16 at 7:27
1
\$\begingroup\$

C, 23 bytes

A more portable (I think) 23-byte solution in C:

f(n){return(n|1)%2-!n;}
\$\endgroup\$
1
\$\begingroup\$

C#, 40 bytes

b=>System.Console.Write(b>0?1:b<0?-1:0);

Or with a built-in:

C#, 44 bytes

using System;b=>Console.Write(Math.Sign(b));

Unfortunately it's longer, then the first solution.

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

MATLAB + Octave, 15bytes

There are a few other Octave/MATLAB answers, but two of the others are simply using a built in, and the other is significantly longer.

The anonymous function:

@(a)(a>0)-(a<0)

Quite simple. If a>0, the answer will be (1-0)=1. If a<0, the answer will be (0-1)=-1. If a==0 the answer will be (0-0)=0.

You can try online here. Simply run the above code and then try with ans(input).

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

Java 8, 33, 17, 14 bytes

i->i>0?1:i>>31

Does not rely on any questionable code constructs or fragments. This is a complete functional interface implementation.

\$\endgroup\$
  • \$\begingroup\$ You can reduce to (int i)->i<0?-1:i>0?1:0 (or even further to i->i<0?-1:i>0?1:0) which are all accepted solutions here on codegolf (codegolf.stackexchange.com/a/16100/16236). \$\endgroup\$ – Olivier Grégoire Dec 24 '16 at 0:23
  • \$\begingroup\$ @OlivierGrégoire thanks, for some reason I was not thinking "this is a single expression, so the lambda can be reduced." \$\endgroup\$ – user18932 Dec 24 '16 at 19:12
  • \$\begingroup\$ It can be reduced to this: i->i>0?1:i>>31 (14 bytes) \$\endgroup\$ – Kevin Cruijssen Jan 10 '17 at 10:49
1
\$\begingroup\$

Scala, 16 bytes

n=>n compareTo 0
\$\endgroup\$
1
\$\begingroup\$

Common Lisp, 21 6 bytes

signum

Try it online!

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

dc, 22 bytes

[pq]sqd0=qdd*vr1-d*v-p

Try it online!

I don't like that 10 bytes of this is eaten up testing for zero, will continue to mull over that. The second half, dd*vr1-d*v-p uses the square root of the square to calculate the absolute value of both our value to test and that value less one. Subtracting the latter from the former yields 1 for a positive value, -1 for a negative.

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

Aceto, 4 bytes

riyp
ri reads input as integer
y puts sign on stack
p prints it

Try it online!

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

GolfScript, 13 bytes

~.{.abs/}{}if

Try it online!

How it Works

Divide by itself if 0 otherwise do nothing, and leaving a zero on the stack to be printed.

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