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

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.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## 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 ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

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

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

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

var OVERRIDE_REG = /^Override\s*header:\s*/i;

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

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      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],
        link: a.share_link,
      });
    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;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    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)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

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

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

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

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
12
  • 49
    \$\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\$ Dec 20, 2016 at 10:10
  • 8
    \$\begingroup\$ This could probably use a leaderboard. \$\endgroup\$ Dec 20, 2016 at 11:13
  • 3
    \$\begingroup\$ @MrLister upvote how you want, but really you should look for creativity instead of code length. \$\endgroup\$
    – FlipTack
    Dec 28, 2016 at 20:13
  • 3
    \$\begingroup\$ @FlipTack Oh, I thought it was codegolf. \$\endgroup\$
    – Mr Lister
    Dec 28, 2016 at 20:23
  • 4
    \$\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, 2016 at 20:25

183 Answers 183

1 2
3
4 5
7
2
\$\begingroup\$

CJam, 1 byte

g

Try it online!

Another built-in, just for the sake of completeness.

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

Wonder, 4 bytes

sign

Usage:

sign 1

Builtin.

Bonus solution (no builtin), 7 bytes

tt cmp0

Usage:

(tt cmp0)5

Uses a compare function with 0.

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

Javascript, 18 bytes

x=>x/Math.abs(x)|0

x/Math.abs(x) is always 1 if x is positive and -1 if x is negative. If x is 0, it returns Nan, which we transform to 0 with the |0 bit.

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

Gema, 9 characters

Just a rewrite of Jordan's Sed solution.

0=0
<D>=1

Sample run:

bash-4.3$ gema '0=0;<D>=1' <<< $'-303\n-12\n-5\n0\n1\n20\n404'
-1
-1
-1
0
1
1
1

Gema, 19 characters

*=@cmpn{*;0;-1;0;1}

Posted just because Gema has a nice function for this task:

@cmpn{number;number;less-value;equal-value;greater-value}
Compare numbers.

Sample run:

bash-4.3$ gema '*=@cmpn{*;0;-1;0;1}' <<< -303
-1

bash-4.3$ gema '*=@cmpn{*;0;-1;0;1}' <<< 0
0

bash-4.3$ gema '*=@cmpn{*;0;-1;0;1}' <<< 404
1
\$\endgroup\$
2
\$\begingroup\$

Batch, 23 bytes

@cmd/cset/a"%1>>31|!!%1

>>31 evaluates to -1 if the input is negative and 0 if it is positive, while !! evaluates to 1 if it is nonzero and 0 if it is zero, so we just have to bitwise OR the two results together.

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

Java 1.8, 11 bytes

Math.signum

In the comments, some people pointed out that this might not technically be valid, if so, here's another version at 12 bytes:

Math::signum
\$\endgroup\$
9
  • \$\begingroup\$ This is not a full program neither an (anonymous) function, but rather just a code excerpt, which can not be reused directly, so I guess this does not qualify. \$\endgroup\$
    – zeppelin
    Dec 20, 2016 at 21:29
  • 3
    \$\begingroup\$ It is technically a function, just referencing an already existing one, you can call it the same way as an anonymous function, but I don't know if such solutions are/should be allowed. \$\endgroup\$
    – nyuszika7h
    Dec 20, 2016 at 22:15
  • \$\begingroup\$ @zeppelin From everything I've seen, this is as acceptable as a loose anonymous function. \$\endgroup\$ Dec 20, 2016 at 22:22
  • \$\begingroup\$ It would be acceptable in a language like Javascript, where evaluating the expression like "Math.sign" will evaluate to a function reference, which you can then invoke or assign to a variable. But (AFAIK) 'Math.signum' does not make a valid standalone expression in Java. Probably you can replace it with a "method reference" (i.e. Math::signum) which will produce a Function<>, which can then be assigned to a variable and invoked, to make it qualify. \$\endgroup\$
    – zeppelin
    Dec 21, 2016 at 9:17
  • 1
    \$\begingroup\$ None of the solutions seem valid to me. The first for the reasons mentioned above. The second because the output is not 1, -1 or 0 but 1.0, -1.0 or 0.0. \$\endgroup\$ Dec 24, 2016 at 0:15
2
\$\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
  • 1
    \$\begingroup\$ A 17-byte alternative, but only works on GNU AWK (gawk): !$0||sub(/\w+/,1) \$\endgroup\$
    – PauloVlw
    May 7, 2021 at 18:38
2
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! If you replace / with //, you don't need to cast to int. \$\endgroup\$
    – Dennis
    Dec 22, 2016 at 3:01
  • \$\begingroup\$ 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. \$\endgroup\$
    – Cormac
    Dec 22, 2016 at 3:15
  • \$\begingroup\$ Right, that returns a float. Nothing wrong with that, I guess. \$\endgroup\$
    – Dennis
    Dec 22, 2016 at 3:18
  • \$\begingroup\$ 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)! \$\endgroup\$
    – user45941
    Dec 23, 2016 at 14:40
2
\$\begingroup\$

GNU sed, 17 15 14 bytes

-2 bytes thanks to zeppelin. -1 byte thanks to manatwork.

/^0/!s/\w\+/1/

Try it online!

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

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.

\$\endgroup\$
3
  • \$\begingroup\$ That's basically a duplicate of Jordan's solution (which is 14 bytes). \$\endgroup\$
    – zeppelin
    Dec 24, 2016 at 10:19
  • \$\begingroup\$ Oh. Damn. ☹ Should I remove mine then? \$\endgroup\$ Dec 24, 2016 at 16:38
  • \$\begingroup\$ 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. \$\endgroup\$
    – zeppelin
    Dec 24, 2016 at 21:32
2
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Nice First Answer! Welcome to the site. \$\endgroup\$
    – Wheat Wizard
    Dec 25, 2016 at 4:54
  • \$\begingroup\$ Is there a reason for the space between the . and _ ? Seems like you could save a byte. \$\endgroup\$ Jan 4, 2017 at 0:52
  • \$\begingroup\$ Also, you can move one character into the 2 "#@ #" to make "#@!#" instead of "!#@ #". Nice answer though! \$\endgroup\$ Jan 4, 2017 at 5:00
  • \$\begingroup\$ 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) \$\endgroup\$ Jan 6, 2017 at 7:21
2
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can save 3 bytes by replacing pred with (1-) which allows you to replace (`compare`0) with compare 0. \$\endgroup\$
    – 0 '
    Oct 20, 2017 at 7:27
2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ 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). \$\endgroup\$
    – user45941
    Dec 23, 2016 at 14:58
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\$
1
  • \$\begingroup\$ This fails, by outputting the inverse sign. However, this is correct, and is the same length. \$\endgroup\$ Oct 31, 2017 at 18:42
2
\$\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\$
0
2
\$\begingroup\$

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.

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

Whitespace, 73 72 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).

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

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
\$\endgroup\$
2
\$\begingroup\$

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.

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

asm2bf, 91 bytes

Takes input as a string on the input (i.e. 1234). Assumes no leading zeros.

in_ r1
mov r2,r1
eq_ r2,.0
eq_ r1,.-
jnz r1,%m
jnz r2,%z
out .+
end
@m
out .-
end
@z
out .0

Try it online!

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

Java, 12 bytes

Long::signum

Try it online!

Using Long instead of Integer saves 3 bytes.

Long.signum documentation

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

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
\$\endgroup\$
2
\$\begingroup\$

BitCycle -U, 8 bytes

?v
/=
>!

Try it here!

Explanation

BitCycle's -U flag represents signed integer inputs as follows:

  • Positive integer \$N\$: a stream of \$N\$ 1's
  • Negative integer \$-N\$: 0 followed by a stream of \$N\$ 1's
  • Zero: 0

So all we need to do is output the leading 0 (if any) and the first 1 (if any), and discard the rest of the 1's.

The switch device (=) is very convenient for this task. The first bit that hits a switch passes straight through, but it also activates the switch in one of two directions: a 0 bit turns the switch into {, which redirects all subsequent bits westward, while a 1 bit turns the switch into }, which redirects all subsequent bits eastward.

In our program, we direct the input from the source ? into the switch =, moving southward. The first bit (either the leading 0 or a 1 if there is no leading 0) goes straight through to the sink ! and is output. Then:

  • If the first bit was a 1 (positive number), the switch activates as }, which redirects the remaining bits off the playfield.
  • If the first bit was a 0 (non-positive number), the switch activates as {, which redirects the remaining bits westward into the splitter /. This device sends the first bit that hits it southward, where it is redirected into the sink and output. All subsequent bits that reach the splitter pass through it and off the playfield.
\$\endgroup\$
2
\$\begingroup\$

Python 3, 28 24 bytes

-4 bytes thanks to @Manny Queen

lambda n:n and abs(n)//n

Try it online!

\$\endgroup\$
0
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\$
0
1
\$\begingroup\$

WolframAlpha, 3 bytes

Try it online: sgn

\$\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\$
2
  • \$\begingroup\$ I think the arithmetic solution I used for my ><> answer and one of my Labyrinth answers would be 2 bytes shorter. \$\endgroup\$ Dec 20, 2016 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\$ Dec 20, 2016 at 14:54
1 2
3
4 5
7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy