57

I was asked in an interview, how to determine whether a number is positive or negative. The rules are that we should not use relational operators such as <, and >, built in java functions (like substring, indexOf, charAt, and startsWith), no regex, or API's.

I did some homework on this and the code is given below, but it only works for integer type. But they asked me to write a generic code that works for float, double, and long.

 // This might not be better way!!

 S.O.P ((( number >> 31 ) & 1) == 1 ? "- ve number " : "+ve number );

any ideas from your side?

skomisa
  • 16,436
  • 7
  • 61
  • 102
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112
  • 3
    If there is a way to convert [whatever] to an array of bits, you could look at the most-significant-bit to determine whether or not the number is positive/negative... Out of curiosity, how would a skill like this help you? I haven't had a job yet but... it seems weird that they would take away basic operators from you :P – Warty Oct 22 '10 at 06:53
  • 147
    stupid contrived interview question – Mitch Wheat Oct 22 '10 at 06:54
  • 4
    @ItzWarty "how would a skill like this help you? " , the curiosity is because ,after having 5 yrs experience in j2ee (i was interviewed for java position and certainly did not expect this question from them :( ) , i felt bad of not able to give solution having CS background – Dead Programmer Oct 22 '10 at 07:01
  • 1
    @Mitch :) thanks , i hope the interviewer would be looking at this question. – Dead Programmer Oct 22 '10 at 07:02
  • I don't think they'd let you use the ternary operator if you cannot use an if statement ... your statement is no different than using an if/else. – Beep beep Oct 22 '10 at 07:32
  • 1
    @Mitch et al - the reason people ask questions like this is to try to see how good you are at figuring out novel solutions to tricky problems. The problem is contrived, but they are more interested in the way you approach the problem than whether you get the right answer. – Stephen C Oct 22 '10 at 07:34
  • 2
    @Stephen C: I understand the reason. Companies like Google, Microsoft etc learned that these weren't the 'right' sort of interview questions many years ago... – Mitch Wheat Oct 22 '10 at 07:48
  • 1
    @Mitch Wheat, I feel that these questions are sort of like asking the person you are interviewing to "Rearrange these sticks, which are in the formation of a camel, to draw the Loch Ness monster"... Sure, they show that the person is able to think "out of the box"... but where in real life [or work, rather] is this useful? – Warty Oct 22 '10 at 08:16
  • 1
    Something that might help you brainstorm: http://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign ... The sizeof operator is always used there, though, and Java [afaik] doesn't have anything like this =/ – Warty Oct 22 '10 at 08:21
  • Are Java numbers always signed? If so, can't you just convert the number to bytes and get the signed bit? Or am I missing something? –  Oct 22 '10 at 08:23
  • @Itzwarty thanks for the link.But in title it says Integer. – Dead Programmer Oct 22 '10 at 08:25
  • @Dalin, that would require the use of an API, though [conversion from integer to 4 bytes]. Also, afaik, you can't do anything like *(byte*)(intptr) to get the most significant byte... Note that the logic has to work for both 32-bit and 64-bit data types =/ – Warty Oct 22 '10 at 08:44
  • What the input is? char[], string, int, or else ?? – Dennis C Oct 22 '10 at 09:14
  • 8
    however, the question of the interviewer was not precise enough. quote: "we should not use conditional operators". this "==" is also a conditional operator. So it is not possible to answer this question at all. the two operators in brackets (<,>) are not a proper explanation at all. The interviewer must have used words to precise his meaning, like: "Regarding conditional operators You are only allowed to use the == operator". To investigate unprecise questions is *the skill* that is really needed in programmers-life. – OlimilOops Oct 22 '10 at 09:18
  • 1
    Interviewer: "I've seen this neat trick in Java yesterday. I want you to read my mind and perform it for me. Can't do that, huh? Huh?" Hypothetical me as the applicant: [runs away]. – Piskvor left the building Oct 22 '10 at 15:06
  • 1
    It's a particularly stupid question in Java. C or C++, maybe. But not in Java. If it is solvable without bit fiddling, then it's a math problem, and language is irrelevant. – Chris Cudmore Oct 22 '10 at 16:39
  • @Suresh, pick one answer if you think it is time to close the question. That's how it worked around here, you know :) – nanda Oct 26 '10 at 07:02
  • 1
    `boolean isPositiveOrNegative(double number) { return number != 0; }` – user85421 Nov 19 '10 at 12:32
  • Translated, the question would be *how would you go about reinventing the wheel? mind you, it has to be in a very contrived way!* – CAFxX Oct 10 '12 at 19:25
  • @SureshSankar : I understand ! I have been to the same office for an interview for a java position as well. The Geeks over there do not seem like they are hiring. They seem like to be in " I know the answer to a really tough question. let me see if you know that?." kind of mentality.If you got the answer to such a question,they say,"Have you seen this question already in the internet?".And if you dont,"You have to brush up your basics. Keep trying . Better luck next time". Any way irrelevent cosnspicuous questions make up an interview ;) Cheers man ;) – Achilles Feb 13 '13 at 05:06
  • Bear in mind that the solutions below *are for Java*. Other languages have different and often trickier (such as the case of C, C++, or JavaScript) rules. – Thanatos Nov 11 '13 at 08:46
  • @OlimilOops Regarding _...this "==" is also a conditional operator..._, it isn't; "==" is a **relational** operator, as are `<` and `>`. The question had been wrong for 10 years by incorrectly stating _"we should not use **conditional** operators such as `<`, and `>`"_. – skomisa Apr 12 '20 at 03:56

32 Answers32

67

The integer cases are easy. The double case is trickier, until you remember about infinities.

Note: If you consider the double constants "part of the api", you can replace them with overflowing expressions like 1E308 * 2.

int sign(int i) {
    if (i == 0) return 0;
    if (i >> 31 != 0) return -1;
    return +1;
}
int sign(long i) {
    if (i == 0) return 0;
    if (i >> 63 != 0) return -1;
    return +1;
}
int sign(double f) {
    if (f != f) throw new IllegalArgumentException("NaN");
    if (f == 0) return 0;
    f *= Double.POSITIVE_INFINITY;
    if (f == Double.POSITIVE_INFINITY) return +1;
    if (f == Double.NEGATIVE_INFINITY) return -1;

    //this should never be reached, but I've been wrong before...
    throw new IllegalArgumentException("Unfathomed double");
}
TT--
  • 2,956
  • 1
  • 27
  • 46
Craig Gidney
  • 17,763
  • 5
  • 68
  • 136
  • 7
    the double solution is very clever/slick – Ivan Oct 22 '10 at 15:27
  • 2
    Based on prior comments on other answers, We could say the Double.POSITIVE_INFINITY is part of the API. I do like it. Could be made complete generic via a (double) cast. – Chris Cudmore Oct 22 '10 at 17:05
  • I like the double solution too! However, the first two methods should return boolean to compile. – David J. Liszewski Oct 22 '10 at 17:39
  • @unhillbilly Whoops. I didn't run the int methods through an actual compiler. Fixed now. – Craig Gidney Oct 22 '10 at 19:49
  • 1
    @chris There's a note that the named double constants can be replaced with literal expressions. I'm not killing the clarity unless it's necessary. – Craig Gidney Oct 22 '10 at 19:50
  • @David It checks if the sign bit is set or not, by shifting it from the highest bit position (31) to the lowest bit position (0). See the [two's complement](http://en.wikipedia.org/wiki/Two%27s_complement) representation and [logical shift](http://en.wikipedia.org/wiki/Logical_shift) operation articles on wikipedia for more information. – Craig Gidney Jan 29 '13 at 02:02
  • Oh so you're shifting by 31 because integers are 32 bit? – David G Jan 29 '13 at 02:43
  • You use the conditional operators == and != which are not allowed in the question. – Konrad Höffner Jun 05 '13 at 10:49
  • @kirdie It's clear from the context of the question that == and != are allowed. The example solution from the question even includes one. I have no idea how you'd do it without them, either, since there don't seem to be any floating point operations that can turn Double.PositiveInfinity into a finite positive value (like the result of 1 you need in that case). – Craig Gidney Jun 05 '13 at 16:47
  • 1
    This is very helpful thanks. This tells me that I shouldn't not be using ">0" and "<0". – jjz Aug 27 '15 at 15:53
  • I don't understand this line: `if (f != f) throw new IllegalArgumentException("NaN");`, why isn't this always false? Can someone explain please? Thanks. – Nom1fan Jun 14 '20 at 09:38
  • 1
    @Nom1fan https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN – Craig Gidney Jun 14 '20 at 10:04
36

The following is a terrible approach that would get you fired at any job...

It depends on you getting a Stack Overflow Exception [or whatever Java calls it]... And it would only work for positive numbers that don't deviate from 0 like crazy.

Negative numbers are fine, since you would overflow to positive, and then get a stack overflow exception eventually [which would return false, or "yes, it is negative"]

Boolean isPositive<T>(T a)
{
  if(a == 0) return true;
  else
  {
    try
    {
      return isPositive(a-1);
    }catch(StackOverflowException e)
    {
      return false; //It went way down there and eventually went kaboom
    }
  }
}
Warty
  • 7,237
  • 1
  • 31
  • 49
  • 27
    That one made ma laugh. :D – Rekin Oct 22 '10 at 07:16
  • 6
    thanks, but it is like blowing a bomb and knowing the result. – Dead Programmer Oct 22 '10 at 07:17
  • 7
    What if number is `1.5` ,it won't result in 0 in any case directly, `0.5` and `-0.5` you should consider that also, otherwise nice idea:) – jmj Oct 22 '10 at 07:19
  • 1
    @Suresh S, did they say your code had to be "efficient"?; @org.life.java: grah, you got me :P – Warty Oct 22 '10 at 07:33
  • @Suresh S @ItzWarty Check mine solution, no need to lighten up bomb :) – jmj Oct 22 '10 at 07:36
  • @ItzWarty nothing on efficiency of code, but should work for higher numbers(scientific numbers),that's what he said and went out after giving this question:|. – Dead Programmer Oct 22 '10 at 07:38
  • This solution won't work for `1.5` or for any such real number – jmj Oct 22 '10 at 07:52
  • 1
    It won't work for 0.0001, will it? Any number that is positive and non-integer that is... – Jason Goemaat Oct 22 '10 at 08:09
  • you people know this http://img3.visualizeus.com/thumbs/09/02/04/code,review,illustration,wtf,b,w-ffde58dd8d68cad42fa1ea4309196e6d_h.jpg ? I'm like "Wtf is this shit?!" now. – Andrei Rînea Nov 02 '10 at 23:43
  • Why would this throw a stack overflow? Wouldn't it just keep going with the recursion until it loops back to zero and returns true? – user3932000 Jan 07 '17 at 16:04
  • Hah, forgot this post existed. The call stack has a finite size. Imagine it's 1MB, for example. Heck, imagine it's 128MB (which is pretty huge). Then if you're counting upwards from, say, 1, until you reach 0, you're doing roughly 2^32 recursive calls, so even if each stack frame were 1 byte large (in reality they're certainly larger) you're certainly overflowing the stack. – Warty Jan 11 '17 at 06:07
17

This will only works for everything except [0..2]

boolean isPositive = (n % (n - 1)) * n == n;

You can make a better solution like this (works except for [0..1])

boolean isPositive = ((n % (n - 0.5)) * n) / 0.5 == n;

You can get better precision by changing the 0.5 part with something like 2^m (m integer):

boolean isPositive = ((n % (n - 0.03125)) * n) / 0.03125 == n;
nanda
  • 24,458
  • 13
  • 71
  • 90
  • 1
    Pretty cool solution! For the 0/1 you could cast to an integer and if it's equal to 0 or 1 then return true (or something like that). – Beep beep Oct 22 '10 at 08:18
  • Isn't == a conditional operator? – MSpeed Oct 22 '10 at 13:26
  • @billynomates: yes it is. However, looking at the answers, even the non valid answers, you practically don't have solution if you may not use it as well. It is after all not explicitly stated as part of the question – nanda Oct 22 '10 at 13:30
8

You can do something like this:

((long) (num * 1E308 * 1E308) >> 63) == 0 ? "+ve" : "-ve"

The main idea here is that we cast to a long and check the value of the most significant bit. As a double/float between -1 and 0 will round to zero when cast to a long, we multiply by large doubles so that a negative float/double will be less than -1. Two multiplications are required because of the existence of subnormals (it doesn't really need to be that big though).

Nabb
  • 3,434
  • 3
  • 22
  • 32
  • 3
    @nanda Casting a double which is too large to a long will result in the largest representable value of type long as per the Java language specification (negatives behave the same way). Anyway, if num fits within a long, we're pretty much multiplying it to infinity anyway (with the exception of zero). – Nabb Oct 22 '10 at 10:47
  • Since You have answered quickly for subnormal numbers , consider i accepted your answer. – Dead Programmer Oct 26 '10 at 10:54
6

What about this?

return ((num + "").charAt(0) == '-');
Peter Štibraný
  • 32,463
  • 16
  • 90
  • 116
Beep beep
  • 18,873
  • 12
  • 63
  • 78
3
// Returns 0 if positive, nonzero if negative
public long sign(long value) {
    return value & 0x8000000000000000L;
}

Call like:

long val1 = ...;
double val2 = ...;
float val3 = ...;
int val4 = ...;

sign((long) valN);

Casting from double / float / integer to long should preserve the sign, if not the actual value...

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
3

You say

we should not use conditional operators

But this is a trick requirement, because == is also a conditional operator. There is also one built into ? :, while, and for loops. So nearly everyone has failed to provide an answer meeting all the requirements.

The only way to build a solution without a conditional operator is to use lookup table vs one of a few other people's solutions that can be boiled down to 0/1 or a character, before a conditional is met.

Here are the answers that I think might work vs a lookup table:

  • Nabb
  • Steven Schlansker
  • Dennis Cheung
  • Gary Rowe
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
2

This code covers all cases and types:

public static boolean isNegative(Number number) {
    return (Double.doubleToLongBits(number.doubleValue()) & Long.MIN_VALUE) == Long.MIN_VALUE;
}

This method accepts any of the wrapper classes (Integer, Long, Float and Double) and thanks to auto-boxing any of the primitive numeric types (int, long, float and double) and simply checks it the high bit, which in all types is the sign bit, is set.

It returns true when passed any of:

  • any negative int/Integer
  • any negative long/Long
  • any negative float/Float
  • any negative double/Double
  • Double.NEGATIVE_INFINITY
  • Float.NEGATIVE_INFINITY

and false otherwise.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

This solution uses modulus. And yes, it also works for 0.5 (tests are below, in the main method).

public class Num {

    public static int sign(long x) {
        if (x == 0L || x == 1L) return (int) x;
        return x == Long.MIN_VALUE || x % (x - 1L) == x ? -1 : 1;
    }

    public static int sign(double x) {
        if (x != x) throw new IllegalArgumentException("NaN");
        if (x == 0.d || x == 1.d) return (int) x;
        if (x == Double.POSITIVE_INFINITY) return 1;
        if (x == Double.NEGATIVE_INFINITY) return -1;
        return x % (x - 1.d) == x ? -1 : 1;
    }

    public static int sign(int x) {
        return Num.sign((long)x);
    }

    public static int sign(float x) {
        return Num.sign((double)x);
    }

    public static void main(String args[]) {

        System.out.println(Num.sign(Integer.MAX_VALUE)); // 1
        System.out.println(Num.sign(1)); // 1
        System.out.println(Num.sign(0)); // 0
        System.out.println(Num.sign(-1)); // -1
        System.out.println(Num.sign(Integer.MIN_VALUE)); // -1

        System.out.println(Num.sign(Long.MAX_VALUE)); // 1
        System.out.println(Num.sign(1L)); // 1
        System.out.println(Num.sign(0L)); // 0
        System.out.println(Num.sign(-1L)); // -1
        System.out.println(Num.sign(Long.MIN_VALUE)); // -1

        System.out.println(Num.sign(Double.POSITIVE_INFINITY)); // 1
        System.out.println(Num.sign(Double.MAX_VALUE)); // 1
        System.out.println(Num.sign(0.5d)); // 1
        System.out.println(Num.sign(0.d)); // 0
        System.out.println(Num.sign(-0.5d)); // -1
        System.out.println(Num.sign(Double.MIN_VALUE)); // -1
        System.out.println(Num.sign(Double.NEGATIVE_INFINITY)); // -1

        System.out.println(Num.sign(Float.POSITIVE_INFINITY)); // 1
        System.out.println(Num.sign(Float.MAX_VALUE)); // 1
        System.out.println(Num.sign(0.5f)); // 1
        System.out.println(Num.sign(0.f)); // 0
        System.out.println(Num.sign(-0.5f)); // -1
        System.out.println(Num.sign(Float.MIN_VALUE)); // -1
        System.out.println(Num.sign(Float.NEGATIVE_INFINITY)); // -1
        System.out.println(Num.sign(Float.NaN)); // Throws an exception

    }
}
Saul
  • 17,973
  • 8
  • 64
  • 88
1

Untested, but illustrating my idea:

boolean IsNegative<T>(T v) {
  return (v & ((T)-1));
}
Will
  • 73,905
  • 40
  • 169
  • 246
  • I think that should be (v & ((v) - 1)) – Mitch Wheat Oct 22 '10 at 07:12
  • I don't know much Java in this respect; but to make something 'generic' you can use Java generics - the templated argument so it should work on a variety of number widths; then, you want to see if the high bit is set (don't know which bit in a double or float gives the sign, reliably, but it can be worked out - does java support generic specialisations?). So you take -1 as whatever the appropriate width is, and treat that as the high bit flag (there isn't a sizeof() in java iirc). On reflection, I think this code would have to be much uglier to work. – Will Oct 22 '10 at 07:13
  • 2
    Nice idea, but I think it will give you a compilation error. You cannot cast to a type parameter. – Stephen C Oct 22 '10 at 07:38
  • 3
    Yeah, won't work at all. Java generics don't work with primitive tpyes, and arithmetic and bitwise operators don't work on wrapper types, and autounboxing again doesn't work generically. – Michael Borgwardt Oct 22 '10 at 07:41
1

It seems arbitrary to me because I don't know how you would get the number as any type, but what about checking Abs(number) != number? Maybe && number != 0

Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113
1

Integers are trivial; this you already know. The deep problem is how to deal with floating-point values. At that point, you've got to know a bit more about how floating point values actually work.

The key is Double.doubleToLongBits(), which lets you get at the IEEE representation of the number. (The method's really a direct cast under the hood, with a bit of magic for dealing with NaN values.) Once a double has been converted to a long, you can just use 0x8000000000000000L as a mask to select the sign bit; if zero, the value is positive, and if one, it's negative.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • 1
    And if they consider that to be an API, it's time to get your ass out of there and find an employer who isn't utterly retarded. – Donal Fellows Oct 22 '10 at 08:18
  • he he "it's time to get your ass out of there" nice quote.he said dont use API's. – Dead Programmer Oct 22 '10 at 08:22
  • Well, you can't do bitmagic in Java on floats or doubles without going through that particular needle (or something equivalent and nastier). – Donal Fellows Oct 22 '10 at 08:46
  • In particular, Java's *specified* to use round-to-zero when going from floating point to integer, so values like `-1e-20` will be deeply problematic (i.e., they convert to a value of the wrong sign). Math.floor would help, but that's prohibited. Stupid problem. Stupider company for asking it. – Donal Fellows Oct 22 '10 at 08:55
1

one more option I could think of

private static boolean isPositive(Object numberObject) {
Long number = Long.valueOf(numberObject.toString());
return Math.sqrt((number * number)) != number;
}

 private static boolean isPositive(Object numberObject) {
Long number = Long.valueOf(numberObject.toString());
long signedLeftShifteredNumber = number << 1; // Signed left shift
long unsignedRightShifterNumber = signedLeftShifteredNumber >>> 1; // Unsigned right shift
return unsignedRightShifterNumber == number;
}
Siri
  • 207
  • 2
  • 4
1

If it is a valid answer

boolean IsNegative(char[] v) throws NullPointerException, ArrayIndexOutOfBoundException
{ 
  return v[0]=='-'; 
} 
Dennis C
  • 24,511
  • 12
  • 71
  • 99
1

This one is roughly based on ItzWarty's answer, but it runs in logn time! Caveat: Only works for integers.

Boolean isPositive(int a)
{
  if(a == -1) return false;
  if(a == 0) return false;
  if(a == 1) return true;
  return isPositive(a/2);
}
Clark Gaebel
  • 17,280
  • 20
  • 66
  • 93
1

I think there is a very simple solution:

public boolean isPositive(int|float|double|long i){
    return (((i-i)==0)? true : false);
}

tell me if I'm wrong!

HowHigH
  • 145
  • 1
  • 7
1

Try this without the code: (x-SQRT(x^2))/(2*x)

wandarkaf
  • 1,839
  • 20
  • 30
Next
  • 11
  • 1
0

Combined generics with double API. Guess it's a bit of cheating, but at least we need to write only one method:

static <T extends Number> boolean isNegative(T number)
{       
    return ((number.doubleValue() * Double.POSITIVE_INFINITY) == Double.NEGATIVE_INFINITY);
}
shrini1000
  • 7,038
  • 12
  • 59
  • 99
0

Two simple solutions. Works also for infinities and numbers -1 <= r <= 1 Will return "positive" for NaNs.

String positiveOrNegative(double number){
    return (((int)(number/0.0))>>31 == 0)? "positive" : "negative";
}

String positiveOrNegative(double number){
    return (number==0 || ((int)(number-1.0))>>31==0)? "positive" : "negative";
}
IvarR
  • 1
  • 1
0

There is a function is the math library called signnum.

http://www.tutorialspoint.com/java/lang/math_signum_float.htm http://www.tutorialspoint.com/java/lang/math_signum_double.htm

thinklarge
  • 672
  • 8
  • 24
0

It's easy to do this like

private static boolean isNeg(T l) {
        return (Math.abs(l-1)>Math.abs(l));
 }
jamb
  • 186
  • 1
  • 8
0

Write it using the conditional then take a look at the assembly code generated.

jeffo
  • 410
  • 1
  • 3
  • 9
0

Why not get the square root of the number? If its negative - java will throw an error and we will handle it.

         try {
            d = Math.sqrt(THE_NUMBER);
         }
         catch ( ArithmeticException e ) {
            console.putln("Number is negative.");
         }
DreamWave
  • 1,934
  • 3
  • 28
  • 59
0

Well, taking advantage of casting (since we don't care what the actual value is) perhaps the following would work. Bear in mind that the actual implementations do not violate the API rules. I've edited this to make the method names a bit more obvious and in light of @chris' comment about the {-1,+1} problem domain. Essentially, this problem does not appear to solvable without recourse to API methods within Float or Double that reference the native bit structure of the float and double primitives.

As everybody else has said: Stupid interview question. Grr.

public class SignDemo {

  public static boolean isNegative(byte x) {
    return (( x >> 7 ) & 1) == 1;
  }

  public static boolean isNegative(short x) {
    return (( x >> 15 ) & 1) == 1;
  }

  public static boolean isNegative(int x) {
    return (( x >> 31 ) & 1) == 1;
  }

  public static boolean isNegative(long x) {
    return (( x >> 63 ) & 1) == 1;
  }

  public static boolean isNegative(float x) {
    return isNegative((int)x);
  }

  public static boolean isNegative(double x) {
    return isNegative((long)x);
  }

  public static void main(String[] args) {


    // byte
    System.out.printf("Byte %b%n",isNegative((byte)1));
    System.out.printf("Byte %b%n",isNegative((byte)-1));

    // short
    System.out.printf("Short %b%n",isNegative((short)1));
    System.out.printf("Short %b%n",isNegative((short)-1));

    // int
    System.out.printf("Int %b%n",isNegative(1));
    System.out.printf("Int %b%n",isNegative(-1));

    // long
    System.out.printf("Long %b%n",isNegative(1L));
    System.out.printf("Long %b%n",isNegative(-1L));

    // float
    System.out.printf("Float %b%n",isNegative(Float.MAX_VALUE));
    System.out.printf("Float %b%n",isNegative(Float.NEGATIVE_INFINITY));

    // double
    System.out.printf("Double %b%n",isNegative(Double.MAX_VALUE));
    System.out.printf("Double %b%n",isNegative(Double.NEGATIVE_INFINITY));

    // interesting cases
    // This will fail because we can't get to the float bits without an API and
    // casting will round to zero
    System.out.printf("{-1,1} (fail) %b%n",isNegative(-0.5f));

  }

}
Gary
  • 7,167
  • 3
  • 38
  • 57
  • What about the domain:x in (-1,1) – Chris Cudmore Oct 22 '10 at 16:42
  • Also, will your solution work for 64 bit machines? How is an `int` represented on 64 bit platform? – Buhake Sindi Oct 23 '10 at 15:32
  • @The Elite Gentleman As I understand it, it's the JVM specification rather than the underlying hardware that defines the size of the various natives. But this may be different on 64-bit machines - I've not researched this. To be honest, the whole question is flawed since floating point cannot be covered. – Gary Oct 25 '10 at 08:01
  • @The Elite Gentleman You may want to review this SO question: http://stackoverflow.com/questions/400477/on-a-64-bit-machine-is-the-size-of-an-int-in-java-32-bits-or-64-bits – Gary Oct 25 '10 at 08:08
0

I don't know how exactly Java coerces numeric values, but the answer is pretty simple, if put in pseudocode (I leave the details to you):

sign(x) := (x == 0) ? 0 : (x/x)
back2dos
  • 15,588
  • 34
  • 50
0

If you are allowed to use "==" as seems to be the case, you can do something like that taking advantage of the fact that an exception will be raised if an array index is out of bounds. The code is for double, but you can cast any numeric type to a double (here the eventual loss of precision would not be important at all).

I have added comments to explain the process (bring the value in ]-2.0; -1.0] union [1.0; 2.0[) and a small test driver as well.

class T {

   public static boolean positive(double f)
   {
       final boolean pos0[] = {true};
       final boolean posn[] = {false, true};

       if (f == 0.0)
           return true;

       while (true) {

           // If f is in ]-1.0; 1.0[, multiply it by 2 and restart.
           try {
               if (pos0[(int) f]) {
                   f *= 2.0;
                   continue;
               }
           } catch (Exception e) {
           }

           // If f is in ]-2.0; -1.0] U [1.0; 2.0[, return the proper answer.
           try {
               return posn[(int) ((f+1.5)/2)];
           } catch (Exception e) {
           }

           // f is outside ]-2.0; 2.0[, divide by 2 and restart.
           f /= 2.0;

       }

   }

   static void check(double f)
   {
       System.out.println(f + " -> " + positive(f));
   }

   public static void main(String args[])
   {
       for (double i = -10.0; i <= 10.0; i++)
           check(i);
       check(-1e24);
       check(-1e-24);
       check(1e-24);
       check(1e24);
   }

The output is:

-10.0 -> false
-9.0 -> false
-8.0 -> false
-7.0 -> false
-6.0 -> false
-5.0 -> false
-4.0 -> false
-3.0 -> false
-2.0 -> false
-1.0 -> false
0.0 -> true
1.0 -> true
2.0 -> true
3.0 -> true
4.0 -> true
5.0 -> true
6.0 -> true
7.0 -> true
8.0 -> true
9.0 -> true
10.0 -> true
-1.0E24 -> false
-1.0E-24 -> false
1.0E-24 -> true
1.0E24 -> true
Samuel Tardieu
  • 2,071
  • 1
  • 14
  • 17
0

This solution uses no conditional operators, but relies on catching two excpetions.

A division error equates to the number originally being "negative". Alternatively, the number will eventually fall off the planet and throw a StackOverFlow exception if it is positive.

public static boolean isPositive( f)
       {
           int x;
           try {
               x = 1/((int)f + 1);
               return isPositive(x+1);
           } catch (StackOverFlow Error e) {
               return true;

           } catch (Zero Division Error e) {
               return false;
           }


   }
l337x911
  • 171
  • 4
0

What about the following?

T sign(T x) {
    if(x==0) return 0;
    return x/Math.abs(x);
}

Should work for every type T...

Alternatively, one can define abs(x) as Math.sqrt(x*x), and if that is also cheating, implement your own square root function...

Per Alexandersson
  • 2,443
  • 1
  • 22
  • 28
0
if (((Double)calcYourDouble()).toString().contains("-"))
        doThis();
else doThat();
nachtwezen
  • 123
  • 9
  • If I was the interviewer, and the candidate started treating numbers as strings, that would be a red flag. Of course, this is a stupid contrived interview question, so I suppose stupid 'clever' responses are appropriate. – pkaeding Oct 02 '11 at 06:40
  • Seeing the String is the mother of all information carriers/representation forms... (; – nachtwezen Oct 05 '11 at 21:16
-1
static boolean isNegative(double v) {
  return new Double(v).toString().startsWith("-");
}
Curd
  • 12,169
  • 3
  • 35
  • 49
-2
if(antennaHeight.compareTo(Double.valueOf(0))>=0)

In the above code, antennaHeight.compareTo(Double.valueOf(0)) --- this 'll return int, comparing this with 0 gives the solution.

j0k
  • 22,600
  • 28
  • 79
  • 90
-3
if (v < 0) System.out.println("negative"); else System.out.println("positive");