# Output the sign

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.

## The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

## Language Name, N bytes


where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes


If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes


You can also make the language name a link which will then show up in the snippet:

## [><>](https://esolangs.org/wiki/Fish), 121 bytes


/* Configuration */

var QUESTION_ID = 103822; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

function getAuthorName(a) {
return a.owner.display_name;
}

function process() {
var valid = [];

var body = a.body;
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
});
else console.log(body);
});

valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});

var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();

languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});

for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body {
text-align: left !important;
display: block !important;
}

width: 290px;
float: left;
}

#language-list {
width: 500px;
float: left;
}

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• 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. – Stewie Griffin Dec 20 '16 at 10:10
• This could probably use a leaderboard. – Martin Ender Dec 20 '16 at 11:13
• With a challenge such as this, I'd only be impressed if there was an answer that used less than 1 byte. Say, 5 bits or something. That I would upvote. – Mr Lister Dec 22 '16 at 13:13
• @FlipTack Oh, I thought it was codegolf. – Mr Lister Dec 28 '16 at 20:23
• @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 – FlipTack Dec 28 '16 at 20:25

!$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  ## Python 3, 23 bytes lambda n:n and n/abs(n)  I know I can make it shorter by doing (n>0) - (n<0), but everyone else seems do be doing that so I thought I would do something different. • Welcome to Programming Puzzles & Code Golf! If you replace / with //, you don't need to cast to int. – Dennis Dec 22 '16 at 3:01 • Thank you! I just realised I dont even need to casting at all. I thought that if n == 0 it would evaluate to false so I would have to convert it to an int but it turns out it stays as 0. – Cormac Dec 22 '16 at 3:15 • Right, that returns a float. Nothing wrong with that, I guess. – Dennis Dec 22 '16 at 3:18 • Floats are acceptable here, since 1.0 == 1 and -1.0 == -1. Nice job using the rarely-used definition of the sign function as the derivative of the absolute value function (with f(0) = 0 explicitly defined)! – user45941 Dec 23 '16 at 14:40 # GNU sed, 1715 14 bytes -2 bytes thanks to zeppelin. -1 byte thanks to manatwork. /^0/!s/\w\+/1/  Try it online! # GNU Sed, 19 bytes (20 counting the r flag) /^0+$/b;s/[0-9]+/1/


(Using the -r flag)

Translation:

/^0+$/b;  If the number is zero, skip to the end of the script s/[0-9]+/1/  Substitute any other numbers with 1. If it's negative the negative sign will remain too. • That's basically a duplicate of Jordan's solution (which is 14 bytes). – zeppelin Dec 24 '16 at 10:19 • Oh. Damn. ☹ Should I remove mine then? – Claire Cavanaugh Dec 24 '16 at 16:38 • Well, not sure what's the current policy on this (I guess that is described somewhere on Meta), but AFAIK you can keep your answer. – zeppelin Dec 24 '16 at 21:32 # Befunge-93, 23 21 20 bytes Thanks to @Mistah Figgins for saving me two three bytes I'm sure this is further golfable. I'll look at it again in the morning. &:#@!#._0#@:#._1-.@  Try it online! Only takes in one line of input for each run, but that's within spec, I guess. • Nice First Answer! Welcome to the site. – Wheat Wizard Dec 25 '16 at 4:54 • Is there a reason for the space between the . and _ ? Seems like you could save a byte. – MercyBeaucou Jan 4 '17 at 0:52 • Also, you can move one character into the 2 "#@ #" to make "#@!#" instead of "!#@ #". Nice answer though! – MercyBeaucou Jan 4 '17 at 5:00 • You can use the same trick on :#@ # -> #@:# as well. My goal whenever writing befunge 93/98 is no whitespace at all. (he says as his own submission is 7% whitespace) – MercyBeaucou Jan 6 '17 at 7:21 ## Haskell, 23 characters A true approach, not using built-ins but function composition (the dot): (1-).fromEnum.compare 0  (or with more space) (1-) . fromEnum . compare 0  Explanation: compare 0 : partially applying the compare function to the first argument 0 results in a function which takes a number and compares it to 0. (compare 0) n = compare 0 n = LT : if 0 < n EQ : if 0 = n GT : if 0 > n fromEnum : it maps LT to 0, EQ to 1 and GT to 2 (1-) : n -> 1 - n  • You can save 3 bytes by replacing pred with (1-) which allows you to replace (compare0) with compare 0. – 0 ' Oct 20 '17 at 7:27 ## Acc!!, 50 49 bytes N Count i while 45/_ { Write _ 49 } Write 48+_/49  Acc!! reads input from stdin one character code at a time. This program decides what to output simply based on the first character of the input: • If it's -, output -1 • If it's 0, output 0 • Otherwise, output 1 Since Acc!! is a very bare-bones language, we have to use a loop for a conditional and integer division for comparison. ### Commented version # Read a character code from input and store it in _ (the accumulator) N # If that character was a minus sign (ASCII 45), 45/_ will be 1 and this loop will run # If that code was a digit (ASCII 48-57), 45/_ will be 0 and the loop will be skipped Count i while 45/_ { # For negative numbers, output the minus sign Write _ # Set the accumulator to ASCII code of 1 so we will break out of the loop and write a 1 49 } # If the input was 0 (ASCII 48), _/49 will be 0 and the next line will write a 0 # Otherwise, _/49 will be 1 and the next line will write a 1 Write 48+_/49  • Clever - this is the first solution I've seen that takes advantage of the fact that you only need to look at the first byte to determine the output (when using string input). – user45941 Dec 23 '16 at 14:58 # 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. • This fails, by outputting the inverse sign. However, this is correct, and is the same length. – caird coinheringaahing Oct 31 '17 at 18:42 # 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. ## FORTRAN 77, 87 bytes  READ*,I IF(I)1,2,3 1 PRINT*,-1 2 PRINT*,0 3 PRINT*,1 END  It is a nice use for the "harmful" arithmetic if statement. Unfortunately, this lovely feature was obsolete in Fortran 90 and posterior versions. Curiously, gfortran can't handle with this arithmetic if, even if I save the file with .f extension. Therefore, I could not test this code. # Whitespace, 7372 68 bytes [S S S T N _Push_1][S N S _Duplicate_1][S N S _Duplicate_1][T N T T _Read_as_integer][T T T _Retrieve][S N S _Duplicate_input][S N S _Duplicate_input][N T T N _If_negative_jump_to_Label_NEGATIVE][N T S S N _If_0_jump_to_Label_ZERO][S N T _Swap_top_two][T N S T _Print_as_integer][N N N _Exit][N S S N _Create_Label_NEGATIVE][S S T T N _Push_-1][T N S T _Print_as_integer][N N N _Exit][N S S S N _Create_Label_ZERO][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. ### Example runs: Positive: Command Explanation Stack Heap STDIN STDOUT STDERR SSSN Push 1 [1] {} SNS Duplicate top (1) [1,1] {} SNS Duplicate top (1) [1,1,1] {} TNTT Read STDIN as integer [1,1] {1:5} 5 TTT Retrieve at heap 1 [1,5] {1:5} SNS Duplicate top (5) [1,5,5] {1:5} SNS Duplicate top (5) [1,5,5,5] {1:5} NTTN If neg.: Jump to Label_NEG [1,5,5] {1:5} NTSSN If 0: Jump to Label_ZERO [1,5] {1:5} SNT Swap top two [5,1] {1:5} TNST Print top as integer [5] {1:5} 1 NNN Exit [5] {1:5}  Program stops with an error: Label does not exist Try it online (with raw spaces, tabs and new-lines only). Zero: Command Explanation Stack Heap STDIN STDOUT STDERR SSSN Push 1 [1] {} SNS Duplicate top (1) [1,1] {} SNS Duplicate top (1) [1,1,1] {} TNTT Read STDIN as integer [1,1] {1:0} 0 TTT Retrieve at heap 1 [1,0] {1:0} SNS Duplicate top (0) [1,0,0] {1:0} SNS Duplicate top (0) [1,0,0,0] {1:0} NTTN If neg.: Jump to Label_NEG [1,0,0] {1:0} NTSSN If 0: Jump to Label_ZERO [1,0] {1:0} NSSSN Create Label_ZERO [1,0] {1:0} TNST Print top as integer [1] {1:0} 0 error  Program stops with an error: No exit defined Try it online (with raw spaces, tabs and new-lines only). Negative: Command Explanation Stack Heap STDIN STDOUT STDERR SSSN Push 1 [1] {} SNS Duplicate top (1) [1,1] {} SNS Duplicate top (1) [1,1,1] {} TNTT Read STDIN as integer [1,1] {1:-5} -5 TTT Retrieve at heap 1 [1,-5] {1:-5} SNS Duplicate top (-5) [1,-5,-5] {1:-5} SNS Duplicate top (-5) [1,-5,-5,-5] {1:-5} NTTN If neg.: Jump to Label_NEG [1,-5,-5] {1:-5} NSSN Create Label_NEG [1,-5,-5] {1:-5} SSTTN Push -1 [1,-5,-5,-1] {1:-5} TNST Print top as integer [1,-5,-5] {1:-5} -1 NNN Exit [1,-5,-5] {1:-5}  Program stops with an error: Label does not exist Try it online (with raw spaces, tabs and new-lines only). # Brain-Flak, 40 38 bytes {<>(())<>{(([{}[]]))<>([{}])<>}}<>({})  Try it online! A bit longer at 50 bytes, but here's a version that acts only on the top value of the stack, returning 0, -1 or 1 depending on the sign of the number. ({<({}([(())])){({}([{}([{}])]))}{}{}>{}(<()>)}{})  ### How it Works: { If number is not 0 <>(())<> Push 1 to the other stack as the sign { While number != 0 (([{}[]])) Push -(number+stack height) twice <>([{}])<> Negate sign, alternating it between -1 and 1 } end while }<>({}) Switch to other stack and force a 0 if the stack is empty  # J, 2 bytes %|  ## Explanation It's a hook, so I'll explain it as y%(|y).  (|y) NB. Magnitude of y. y% NB. y/abs(y)  Oh, yes, I am learning J. I want to golf in android and building my own golfing language is hard, so I started learning J. # Java, 12 bytes Long::signum  Try it online! Using Long instead of Integer saves 3 bytes. Long.signum documentation # BRASCA, 8 bytes ,'/-1$%n


Try it online!

## Explanation

,            - Reverse the stack to take the first character from input
'/-         - Subtract it by 47
1$% - 1 % that value n - And output it  # Japt, 2 bytes Ug  Test it online! U is the input number, and g is the sign function on numbers. Output is implicit. # Pyth, 2 bytes ._  herokuapp Pyth's sign function. ## Matlab, 4 bytes sign  Matlab as well has a builtin for it. # Octave, 4 bytes As with many others, a built-in: sign  Please, read the first sentence of this meta post before voting. # WolframAlpha, 3 bytes Try it online: sgn # 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. • I think the arithmetic solution I used for my ><> answer and one of my Labyrinth answers would be 2 bytes shorter. – Martin Ender Dec 20 '16 at 13:46 • 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.) – Martin Ender Dec 20 '16 at 14:54 # SAS Macro Language, 43 bytes In the extremely wordy language... %macro s(n);%put(%sysfunc(sign(&n)));%mend;  ## 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! 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)))  # 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.

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

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


## Javascript, 37 bytes

function s(n){return n>0?1:n<0?-1:0}

• Sorry, updated! – Ostbullen Dec 21 '16 at 15:35
• You could use a lambda: n=>n>0?1:n<0?-1:0 – user45941 Dec 23 '16 at 14:45

## brainfuck, 23 bytes

-<,
[
[
>-[-<]
>
]
->[>+>]
]
<.


This takes a single byte from stdin and interprets it as a signed char, printing \xff for negative, \x00 for zero, and \x01 for positive.

Try it online.

Viewed as an unsigned char, we are checking whether it is greater than 127, with 0 as a special case. We can do the comparison by decrementing from 255 twice at a time.

• Doing I/O as decimal strings could be fun too. – Mitch Schwartz Dec 21 '16 at 16:48
• You could argue that all numbers in BF are positive, so ,>+. is a valid answer. – Esolanging Fruit Dec 22 '16 at 4:38
• @Challenger5 Even if that were modified to handle zero, e.g. with ,[>+>]<., I don't think that could be argued as anything other than a loophole. – Mitch Schwartz Dec 22 '16 at 5:49
• Definitely, but it's funny. – Esolanging Fruit Dec 22 '16 at 5:50
• @Challenger5 That would be abusing native number types to trivialize the challenge. The solution Mitch has used (interpreting the input as an 8-bit two's complement integer) is valid, and the only valid way to do this in brainfuck other than interpreting decimal strings (unless there's another way and I'm not seeing it). – user45941 Dec 23 '16 at 14:44

# MarioLANG, 868 bytes

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


;[>
==                                                                                                   output zero
[@                                                                                            :                                                                      * start
move pointer back to arg  ))    <
=================================================================================="===
increase counter limit
@   ((((++
=================    set counters
<
@ -)+)+)+ ((([! ))+((
==============#======
reset limit
(<
======="
@ +)-   [! )))
=========#====   try subtraction
)  <
==========="
> ( [! )
"====#==
========#                   ))  <
==============="
> (( [!  !
"=====#==#
@  +((-)) [!
===========#

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)