Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
28  
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 at 10:10
5  
This could probably use a leaderboard. – Martin Ender Dec 20 at 11:13
1  
@MartinEnder I use the userscript, so there's a builtin leaderboard. If you want to add the stack snippet, feel free. – Mego Dec 20 at 14:39
    
do we have to account for leading zeroes? – Destructible Watermelon 2 days ago
    
@DestructibleWatermelon No – Mego 2 days ago

83 Answers 83

C, 24 23 bytes

Thanks to @aross for saving a byte!

f(n){return n>>31|!!n;}

Sigh.

Not guaranteed to work on all systems, works on TIO.

share|improve this answer
4  
@betseg That is because upvotes on built-ins are now frowned upon. – Erik the Outgolfer Dec 20 at 11:41
2  
I was hoping for "Trivial solutions are frowned upon", but well.. Better than nothing. :) – Stewie Griffin 2 days ago
1  
Saving 1 byte with this return n>>16|!!n; – aross 2 days ago
1  
Size of int is compiler dependent, 16 won't work on most modern systems. – G B 2 days ago
4  
@GB Size of int is probably either 2 (16, x86) or 4 (32, x86_64) but remember, all that's needed is an architecture on which it is valid. This isn't Stack Overlflow, portability is not important. – cat yesterday

Retina, 9 bytes

[1-9].*
1

Try it online!

Replaces a non-zero digit and everything after it with 1. This leaves a potential leading - intact and changes all numbers except 0 itself to absolute value 1.

share|improve this answer
    
This is very clever :) – Mego 5 hours ago

COW, 225 213 201 bytes

oomMOOmoOmoOmoOmoOMoOMoOmOomOomOoMoOMMMmoOMMMMOOMOomOo
mOoMOomoOmoOmoomOomOoMMMmoOmoOmoOMMMMOOOOOmoOMOoMOomOo
mOomOoMoOMMMmoOMMMMOOMOomOomOoMoOmoOmoOmoomoOmoomOomOo
mOomoomoOMOOmoOmoOmoOMOoMMMOOOmooMMMOOM

Try it online!

The way that this code works is that it determines the sign by alternating adding and subtracting bigger numbers, and seeing which one was the last one that worked. Given any non-zero integer, first subtract 1, then add 2, then subtract 3, etc. and you'll eventually reach 0. Keep track of your state by alternating adding and subtracting 2 to a value that starts off at 0. For example:

-5  - 1  = -6  (current state: 0 + 2 = 2)
-6  + 2  = -4  (current state: 2 - 2 = 0)
-4  - 3  = -7  (current state: 0 + 2 = 2)
-7  + 4  = -3  (current state: 2 - 2 = 0)
-3  - 5  = -8  (current state: 0 + 2 = 2)
-8  + 6  = -2  (current state: 2 - 2 = 0)
-2  - 7  = -9  (current state: 0 + 2 = 2)
-9  + 8  = -1  (current state: 2 - 2 = 0)
-1  - 9  = -10 (current state: 0 + 2 = 2)
-10 + 10 =  0  (current state: 2 - 2 = 0)
value is now at 0.  state - 1 = 0 - 1 = -1
sign of original number is -1

When you're done, subtract 1 from your state and you get the sign, positive or negative. If the original number is 0, then don't bother doing any of this and just print 0.

Detailed Explanation:

oom                                        ;Read an integer into [0]
MOO                                        ;Loop while [0] is non-empty
    moOmoOmoOmoOMoOMoOmOomOomOo            ;    Decrement [4] twice
    MoOMMMmoOMMM                           ;    Increment [1], then copy [1] to [2]
    MOO                                    ;    Loop while [2] is non-empty
        MOomOomOoMOomoOmoO                 ;        Decrement [0] and [2]
    moo                                    ;    End loop now that [2] is empty
    mOomOoMMMmoOmoOmoOMMM                  ;    Navigate to [0], and copy to [3]
    MOO                                    ;    Perform the next steps only if [3] is non-zero
        OOOmoOMOoMOomOomOomOoMoOMMMmoOMMM  ;        Clear [3], increment [4] twice, increment [1], and copy it to [2]
        MOO                                ;        Loop while [2] is non-empty
            MOomOomOoMoOmoOmoO             ;            Decrement [2] and increment [0]
        moo                                ;        End loop now that [2] is empty
    moO                                    ;        Navigate back to [3]
    moo                                    ;    End the condition
    mOomOomOo                              ;    Navigate back to [0]
moo                                        ;End loop once [0] is empty.
moO                                        ;Navigate to [1]. If [1] is 0, then input was 0.  Otherwise, [4] contains (sign of [0] + 1)
MOO                                        ;Perform the next steps only if [1] is non-zero
    moOmoOmoOMOoMMMOOO                     ;    Navigate to [4], copy it to the register, and clear [4].
moo                                        ;End condition
MMMOOM                                     ;If the register contains something (which is true iff the condition ran), paste it and print it.  Otherwise, no-op and print 0.

I'm still experimenting with golfing it (you will be shocked to discover that golfing in COW is rather difficult), so this may come down a few more bytes in the future.

share|improve this answer

Mathematica, 4 bytes

Clip

How about not using the built-in Sign and still scoring 4 bytes? ;)

Clip with a single argument clips (or clamps) the input value between -1 and 1. Since the inputs will only be integers, this is the same as using Sign.

share|improve this answer
    
+1, pretty neat. – LegionMammal978 2 hours ago

Cubix, 10 bytes

(W0^I?>O2@

Test it online!

This code is wrapped to the following cube net:

    ( W
    0 ^
I ? > O 2 @ . .
. . . . . . . .
    . .
    . .

The code is then run with the IP (instruction pointer) starting on the I, facing east. I inputs a signed integer from STDIN, pushing it onto the stack.

The next command is ?, which changes the direction of the IP depending on the sign of the top item. If the input is 0, it keeps moving in same direction, running through the following code:

  • > - Point the IP to the east. (No-op since we're already going east.)
  • O - Output the top item as an integer.
  • 2 - Push 2 to the stack. This is practically a no-op, because...
  • @ - Terminates the program.

If the input is negative, the IP turns left at the ?; because this is a cube, the IP moves onto the 0 in the second row, heading east. 0 pushes a literal 0, then this code is run:

  • ^ - Point the IP north.
  • W - "Sidestep" the IP one spot to the left.
  • ( - Decrement the top item.

The TOS is now -1, and the IP wraps around the cube through a bunch of no-ops . until it hits the >. This runs the same output code mentioned above, outputting -1.

If the input is positive, the same thing happens as with negative inputs, with one exception: the IP turns right instead of left at the ?, and wraps around the cube to the 2, which pushes a literal 2. This is then decremented to 1 and sent to output.

share|improve this answer
3  
The animation of program flow is very nice! – Luis Mendo Dec 20 at 10:25
    
Nice language. Could it be shorter? 4 flow controls seems much. In operation-count it can be 8 bytes by introducing another ?, but now it uses the bottom half of the cube: ..1nI?..>O@.........? – BlackShift 2 days ago
    
Six is possible if we ignore outputs after the first: /I?nO1 By the way, this only works because I returns -1 in the online interpreter instead of 0 according to the spec. – BlackShift 2 days ago
    
@BlackShift Thanks for your interest! I like your suggestions, but I'm not sure how to improve them. It's definitely possible to use less instructions; the tricky part is using less of the cube... ;-) And thanks for pointing out that -1 bug, I'll get that fixed soon. – ETHproductions yesterday

JavaScript (ES6), 9 bytes

Math.sign

Straightforward.

The shortest non-builtin is 13 bytes:

n=>n>0|-(n<0)

Thanks to @Neil, this can be golfed by a byte, but at the cost of only working on 32-bit integers:

n=>n>0|n>>31

Or you could do

n=>n>0?1:!n-1

which seems more golfable, but I'm not sure how.

share|improve this answer
    
Non-builtin in 12 bytes for 32-bit signed integer n: n=>n>>31|!!n. – Neil 2 days ago
    
@Neil n>>31 is really smart, thanks! – ETHproductions 2 days ago
    
I don't think the third solution is valid, since Javascript uses double-precision floats for numerics. But, I could be wrong. – Mego 6 hours ago
    
@Mego You are correct. I've clarified this in the post. – ETHproductions 4 hours ago
    
@ETHproductions My point was, I don't know of any JS implementation that actually uses 32-bit integers rather than double-precision floats for everything. Bit-shifting like that doesn't work with double-precision floats. – Mego 4 hours ago

Labyrinth, 10 bytes

?:+:)%:(%!

Try it online!

Explanation

Labyrinth's control flow semantics actually give you a "free" way to determine a number's sign, because the chosen path at a 3-way fork depends on whether the sign is negative, zero or positive. However, I haven't been able to fit a program with junctions into less than 12 bytes so far (although it may be possible).

Instead, here's a closed-form solution, that doesn't require any branches:

Code    Comment             Example -5      Example 0       Example 5
?       Read input.         [-5]            [0]             [5]
:+      Double.             [-10]           [0]             [10]
:)      Copy, increment.    [-10 -9]        [0 1]           [10 11]
%       Modulo.             [-1]            [0]             [10]
:(      Copy, decrement.    [-1 -2]         [0 -1]          [10 9]
%       Modulo.             [-1]            [0]             [1]
!       Print.              []              []              []

The instruction pointer then hits a dead end, turns around and terminates when % now attempts a division by zero.

Doubling the input is necessary to make this work with inputs 1 and -1, otherwise one of the two modulo operations would already attempt a division by zero.

share|improve this answer
    
Your code is happy and turns sad :D – Stefan 2 days ago
1  
@Stefan You can change the order if you prefer. ;) – Martin Ender 2 days ago

><>, 9 8 bytes

Thanks to Sp3000 for saving a byte.

'i$-%n/

There's an unprintable 0x01 before the /.

Try it online!

Explanation

This is a port of my character code-based Labyrinth answer.

'     Push the entire program (except ' itself) onto the stack, which ends 
      with [... 1 47].
i     Read the first character of the input.
$-    Subtract the 47.
%     Take the 1 modulo this value.
n     Output the result as an integer.
0x01  Unknown command, terminates the program.
share|improve this answer

Dyalog APL, 1 byte

Works for complex numbers too, returning 1∠θ:

×

TryAPL online!

Without that built-in:

>∘0-<∘0

>∘0 more-than-zero

- minus

<∘0 less-than-zero

TryAPL online!

share|improve this answer
    
You actually did it in ONE byte... You sir, are a legend. I'm sure Jon Skeet would be proud. – Mango 2 days ago
    
@Mango You are joking, right? There are a handful of single-byte answers to this challenge. – Adám 2 days ago
    
I was being sarcastic, also I said that because this is the first single byte answer I saw. – Mango 2 days ago

Vim, 22 bytes

xVp:s/-/-1^M:s/[1-9]/1^M

Saved one byte thanks to @DJMcMayhem!

Here, ^M is a literal newline.

As @nmjcman101 pointed out in the comments, a single regex can be used (:s/\v(-)=[^0].*/\11^M, 20 bytes) instead, but since this is basically the same as a Retina answer would be, I'm sticking to my own method.

Explanation:

xVp                        Delete everything except the first character. If the number is negative, this leaves a -, a positive leaves any number between 1 and 9, and 0 leaves 0.
   :s/-/-1^M               Replace a - with a -1
            :s/[1-9]/1^M   Replace any number between 1 and 9 with 1.

Here's a gif of it running with a negative number (old version):

Running with negative

Here's it running with 0:

Running with zero

Running with positive:

Running with positive

share|improve this answer
1  
I really like your method, but it's possible in a single regex: :s/\v(-)=[^0].*/\11 – nmjcman101 Dec 20 at 16:20

Python 2, 17 bytes

lambda n:cmp(n,0)

Try it online!

share|improve this answer
4  
Oh you ninja'd me. – Jonathan Allan Dec 20 at 6:02
1  
Whoops. Sorry... – Dennis Dec 20 at 6:05
4  
Too bad you can't do (0).__rcmp__ ... – Sp3000 Dec 20 at 8:32
    
You can do -(0).__cmp__ though. – nyuszika7h Dec 20 at 18:57
1  
@nyuszika7h Not quite. Trying to use it as a function raises a TypeError. – Dennis Dec 20 at 18:59

PHP, 16 bytes

Uses the new spaceship operator.

<?=$argv[1]<=>0;
share|improve this answer
    
Don't forget to mention that this is a PHP7 answer only. And since you're using <?=, you should use $_GET[n], which doesn't take any more bytes. To use <?=, you need to be inside a webserver (like Apache), and there you won't have access to $argv. You can try to run <?php var_dump($argv); from a PHP file, acessed through Apache, and it will show NULL. – Ismael Miguel yesterday
1  
"To use <?=, you need to be inside a webserver (like Apache)," No. The <?= operator works just fine from the command line. – Alex Howansky yesterday
    
Running php -r '<?=1' I get PHP Parse error: syntax error, unexpected '<' in Command line code on line 1. But seems to work fine from a file. I guess you are right. – Ismael Miguel yesterday
    
The -r flag is to run a code snippet. This is complete source. Save it to a file and then run php file.php – Alex Howansky yesterday
    
I figured it out already. I really didn't knew that it worked from a file, using the (implicit) -f parameter. – Ismael Miguel yesterday

Brain-Flak 74 42 40 Bytes

Saved 2 bytes thanks to 1000000000

{([({}<([()])>)]<>(())){({}())<>}}{}({})

Try it Online!

Explanation:

{([({}<([()])>)]<>(())){({}())<>}}{}({})
{                                }       # if 0 do nothing
   (          )                          # push:                           
    {}<     >                            # the input, after 
       (    )                            # pushing:
        [  ]                             # negative:
         ()                              # 1

 (                    )                  # Then push:
  [            ]                         # the negative of the input
                <>                       # on the other stack with:
                   ()                    # a 1 
                  (  )                   # pushed under it

                       {        }        # while 1: 
                        ({}())           # increment this stack and...
                              <>         # switch stacks

                                 {}      # pop the top (the counter or 0 from input)
                                   (  )  # push:
                                    {}   # the top (this is a no-op, or pushes a 0)
share|improve this answer
    
    
You can save 2 bytes by removing the zero monad around (()) – 1000000000 1 hour ago
    
@1000000000 Thanks! – Riley 14 mins ago

Perl, 9 bytes

Requires -E at no extra cost.

say<><=>0

Usage

perl -E 'say<><=>0' <<< -9999
-1
perl -E 'say<><=>0' <<< 9999
1
perl -E 'say<><=>0' <<< -0
0

I'm happy with the fish operator!

share|improve this answer
1  
It doesn't really "require" -E, that's only if you call it from the CLI instead of a file, which is why I guess you said no extra cost. – nyuszika7h 2 days ago
    
@nyuszika7h indeed, requires I guess in the way that testing via -e won't work, but -E is accepted as no longer than -e. As per consensus on meta. I hope that helps a little! – Dom Hastings 2 days ago
    
Yeah, I was not suggesting requiring any extra cost for that, as it works fine when that script is executed normally from a file. – nyuszika7h 2 days ago

///, 52 bytes

/2/1//3/1//4/1//5/1//6/1//7/1//8/1//9/1//10/1//11/1/

Ungolfed, explanation:

/2/1/
/3/1/
/4/1/
/5/1/
/6/1/
/7/1/
/8/1/
/9/1/
/10/1/
/11/1/

It's basically a MapReduce implemenatation, i.e. there are two phases:

  • Replace all occurrences of digits 2-9 by 1, e.g. 1230405 -> 1110101
  • Reduce pairs of 11 or 10 to 1 repeatedly, e.g. 1110101-> 1

If there was a - in front initially, it will remain and the output will be -1. A single 0 is never replaced, thus resulting in itself.

Try it online, with test cases

share|improve this answer
    
This is extremely clever! – Mego 6 hours ago

MATL, 6 bytes

0>EGg-

Input may be a number or an array. The result is number or an array with the corresponding values.

Try it online! Or test several cases using array input.

Explanation

This avoids using the builtin sign function (ZS).

0>   % Take input implicitly. Push 1 if positive, 0 otherwise
E    % Multiply by 2
Gg   % Push input converted to logical: 1 if nonzero, 0 otherwise
-    % Subtract. Implicitly display
share|improve this answer
    
MATL is longer than Matlab and Octave?! – Adám Dec 20 at 11:24
2  
He could also have used the built-in ZS as it says in the answer. – Stewie Griffin Dec 20 at 13:53

J, 1 byte

*

Try it online (with test cases)!

share|improve this answer
    
@Mego. Thanks. It is all input, eh? – Adám Dec 20 at 7:33

R, 25 bytes

'if'(x<-scan(),x/abs(x),0)

Takes the number to STDIN. Then checks if it's zero, if not, returns x/|x| which is either 1 of -1, and outputs 0 if x=0.

This is without using the builtin sign of course.

share|improve this answer
1  
Using the builtin is of course shorter, but less fun: sign(scan()). – Billywob Dec 20 at 10:40
    
Sorry, shouldve explicitly mentioned avoiding the builtin – Jarko Dubbeldam Dec 20 at 10:48

Octave, 26 24 bytes

f=@(x)real(asin(x))/pi*2

This is my first Octave answer, any golfing tips are appreciated!

Try it online!

The idea for taking the asin comes from the question where it says output the sign :)

Explanation

Note: dividing the number by pi and multiplying it by 2 is the equivalent of dividing the entire number by pi/2

Case 0:

asin(0) yields 0. Taking the real part of it and dividing it by pi/2 makes no difference to the output.

Case positive:

asin(1) yields pi/2. asin of any number bigger than 1 will give pi/2 + complex number. Taking the real part of it gives pi/2 and dividing it by pi/2 gives 1

Case negative:

asin(-1) yields -pi/2. asin of any number smaller than -1 will give -pi/2 + complex number. Taking the real part of it gives -pi/2 and dividing it by pi/2 gives -1

share|improve this answer
    
@LuisMendo N will be an integer I'm lucky it says that in the question :) – Kritixi Lithos Dec 20 at 13:59
    
Oh, I hadn't read that part :) – Luis Mendo Dec 20 at 14:00
1  
​C​l​e​v​e​r!​​!​ – flawr 2 days ago

Stack Cats, 6 + 4 = 10 bytes

_[:I!:

+4 bytes for the ​ -nm flags. n is for numeric I/O, and since Stack Cats requires programs to be palindromic, m implicitly mirrors the source code to give the original source

_[:I!:!I:]_

Try it online! As with basically all good Stack Cats golfs, this was found by brute force, beat any manual attempts by a long shot, and can't easily be incorporated into a larger program.

Add a D flag if you'd like to see a step-by-step program trace, i.e. run with -nmD and check STDERR/debug.


Stack Cats uses a tape of stacks which are implicitly filled with zeroes at the bottom. At the start of the program, all input is pushed onto the input stack, with a -1 at the base to separate the input from the implicit zeroes. At the end of the program, the current stack is output, except a base -1 if present.

The relevant commands here are:

_           Perform subtraction [... y x] -> [... y y-x], where x is top of stack
[           Move left one stack, taking top of stack with you
]           Move right one stack, taking top of stack with you
:           Swap top two of stack
I           Perform [ if top is negative, ] if positive or don't move if zero. Then
                negate the top of stack.
!           Bitwise negate top of stack (n -> -n-1)

Note that all of these commands are invertible, with its inverse being the mirror of the command. This is the premise of Stack Cats — all nontrivial terminating programs are of odd length, since even length programs self-cancel.

We start with

               v
               n
              -1
...  0    0    0    0    0  ...

_ subtracts, making the top -1-n, and [ moves the result left one stack:

           v
       -1-n   -1
...  0    0    0    0    0  ...

: swaps top two and I does nothing, since the top of stack is now zero. ! then bitwise negates the top zero into a -1 and : swaps the top two back. ! then bitwise negates the top, turning -1-n back into n again:

          v
          n
         -1   -1
...  0    0    0    0    0  ...

Now we branch based on I, which is applied to our original n:

  • If n is negative, we move left one stack and end with -n on an implicit zero. : swaps, putting a zero on top, and ] moves the zero on top of the -1 we just moved off. _ then subtracts, leaving the final stack like [-1 -1], and only one -1 is output since the base -1 is ignored.

  • If n is zero, we don't move and : swaps, putting -1 on top. ] then moves this left -1 on top of the right -1, and _ subtracts, leaving the final stack like [-1 0], outputting the zero and ignoring the base -1.

  • If n is positive, we move right one stack and end with -n on a -1. : swaps, putting the -1 on top, and ] moves this -1 right, on top of an implicit zero. _ then subtracts, giving 0 - (-1) = 1 and leaving the final stack like [1], which is output.

share|improve this answer

V 14 12 bytes

Thanks @DJMcMayhem for 2 bytes. Uses a reg-ex to do the substitution. Kind of fun, because it's not a built-in. I have a more fun function, but it's not working the way I expected.

ͨ-©½0]/±1

Verify Test Cases

This just translates to :%s/\v(-)=[^0].*/\11 which matches one or more - followed by anything but 0, followed by anything any number of times. It's replaced with the first match (so either a - or nothing) and a 1. The regex doesn't match 0, so that stays itself.

The More Fun Way (21 bytes)

é
Àé12|DkJòhé-òó^$/a

TryItOnline

This accepts the input as an argument rather than in the buffer.

é<CR> Insert a new line.

À run the argument as V code. a - will move the cursor to the previous line, and any number will become the count for the next command

é1 insert (count)1's

2| move to the second column

D delete everything from the second column onwards (leaving only one character)

kJ Join the two lines together.

òhé-ò translates to: "run hé- until breaking". If the 1 was on the second line, this breaks immediately after the h. If it was on the first line, it will insert a - before breaking.

ó^$/a This fixes the fact that -1,0,1 will leave a blank, and replaces a blank with the argument register.

share|improve this answer
    
I knew I should have read that page better. It's not actually shorter - I forgot 0, but I was trying to take the number in as an argument and then Àé1. A positive number gives a string of ones, a negative number SHOULD give a string of ones one row up, and 0 would give nothing. The negative number bit didn't work with À, but did with d$@" – nmjcman101 Dec 20 at 17:27
    
Ah. Well the reason that doesn't work is because there isn't another row up for it to go onto. If you add é<cr> it'll have two empty lines and then that does work. I'm not sure if you can use that to get a full answer – DJMcMayhem Dec 20 at 17:40
    
I did have another line to up to, just didn't explicitly say that in my comment. What's the -- argument you added? – nmjcman101 Dec 20 at 17:47
1  
It means "end of options". Since -6 starts with a flag, docopt (the python library for command line options) thinks it's a command-line flag rather than an argument. Adding -- just signals that it's an argument not an option. Otherwise, it won't run at all because of invalid command line invocation. – DJMcMayhem Dec 20 at 17:49

C#, 16 15 bytes

Improved solution thanks to Neil

n=>n>0?1:n>>31;

Alternatively, the built-in method is 1 byte longer:

n=>Math.Sign(n);

Full program with test cases:

using System;

public class P
{
    public static void Main()
    {
        Func<int,int> f =
        n=>n>0?1:n>>31;

        // test cases:
        for (int i=-5; i<= 5; i++)
            Console.WriteLine(i + " -> " + f(i));
    }
}
share|improve this answer
2  
Try n>>31 instead of n<0?-1:0. – Neil 2 days ago
1  
It's a bit sad when the builtin isn't even the shortest solution. – Mego 5 hours ago
    
Let's say C# is known to be rather verbose... – adrianmp 5 hours ago

Ruby, 10 bytes

->x{x<=>0}
share|improve this answer

Jelly, 1 byte

TryItOnline!

The monadic sign atom, , does exactly what is specified for an integer input, either as a full program or as a monadic link (function taking one argument).

share|improve this answer

TI-Basic, 8 bytes

median({1,Ans,~1

Alternative solutions (feel free to suggest more):

max(~1,min(Ans,1               8  bytes
0:If Ans:Ans/abs(Ans           9  bytes
(Ans>0)-(Ans<0                 10 bytes
share|improve this answer
    
What is the ~ supposed to be? – Conor O'Brien yesterday
    
@ConorO'Brien Negative symbol, to differentiate between TI-Basic's subtract symbol. I know that Cemetech SC uses ~ to represent this token as well. – Timtech yesterday
    
Oh, cool. I had no idea. – Conor O'Brien yesterday
    
@ConorO'Brien Well, now you know. Thanks for asking :) – Timtech yesterday
    
This is not valid - using Ans as input does not meet the criteria for being a valid default I/O method (it doesn't have twice as many upvotes as downvotes - currently it's at +19/-12). – Mego 6 hours ago

Actually, 1 byte

s

Try it online!

Another case of exactly what it says on the tin - s is the sign function.

Without the builtin (4 bytes):

;A\+

Try it online!

;A\ divides the absolute value of the input by the input. This results -1 for negative inputs and 1 for positive inputs. Unfortunately, due to Actually's error handling (if something goes wrong, the command is ignored), 0 as input leaves two 0s on the stack. + rectifies this by adding them (which causes an error with anything else, so it's ignored).

share|improve this answer

Mathematica, 4 bytes

Sign

Exactly what it says on the tin

share|improve this answer
    
Save a byte with sgn – Adám Dec 20 at 11:13
1  
WolframAlpha isn't the same as Mathematica; it includes automatic interpretation of ambiguous/natural language input. – Greg Martin Dec 20 at 11:15
    
So I should submit this a separate answer? – Adám Dec 20 at 11:21
    
seems reasonable to me... – Greg Martin Dec 20 at 11:24

05AB1E, 3 bytes

0.S

Try it online!

share|improve this answer

Labyrinth, 8 bytes

1,_47-%!

Try it online!

I'm posting this as a separate answer because my other Labyrinth answer is based on arithmetic on the actual numerical input value, whereas this mostly ignores the number and works with the character code of the first character instead.

Explanation

So yeah, this reads the first character code which is either 45 (-, which should yield -1), 48 (0, which should yield 0) or 49 to 57 (1-9, which should yield 1). This mapping can be accomplished via the simple formula 1 % (x - 47). To see why this works, here is the breakdown of the code for 3 different examples:

Code    Comment             Example -5      Example 0       Example 5
1       Push 1.             [1]             [1]             [1]
,       Read character.     [1 45]          [1 48]          [1 53]
_47-    Subtract 47.        [1 -2]          [1 1]           [1 6]
%       Modulo.             [-1]            [0]             [1]
!       Print.              []              []              []

The instruction pointer then hits a dead end, turns around and terminates when % now attempts a division by zero.

Another simple computation that works:

x -= 46
x %= x-1
share|improve this answer

Mathematica, 28 bytes

Limit[2ArcTan@x#/Pi,x->∞]&

Mathematica, 30 bytes

2HeavisideTheta@#-1/._[_]->1/2&

Mathematica, 76 bytes

Round@Integrate[E^(2#+I t#)/(2+I t)/Pi,{t,-∞,∞},PrincipalValue->True]-1&

Just to be different :)

share|improve this answer
2  
Median@{#,1,-1} and #~Min~1~Max~-1 if you want some more ideas ;) – Martin Ender Dec 20 at 12:09
    
Personal challenge to you: find an implementation that's longer than 76 bytes, but fully golfed for its algorithm (can you be turned to the dark side?!). – Greg Martin Dec 20 at 18:43
    
Can I take you up on this challenge? – Gabriel Benamy 2 days ago
    
Of course! .. :) – Greg Martin 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.