The question, as stated, is ambiguous.
0
is of course the obvious solution, and as others have discussed there are no other solutions in Java (which is how the question is tagged).
In C, for any signed integer type, the minimum value of the given type may be a solution for some implementations. For example, given a 2's-complement representation, evaluating -INT_MIN
will probably give you -INT_MIN
. But in fact, the behavior of evaluating that expression is undefined due to overflow, even if you assume 2's-complement. (Wraparound semantics are very common, but are not guaranteed.) Furthermore, the C standard does not require a 2's-complement representation; it also permits 1's-complement and sign-and-magnitude, neither of which has that extra negative value.
This program:
#include <stdio.h>
#include <limits.h>
int main(void) {
int n = INT_MIN;
printf("%d\n%d\n", n, -n); /* Warning: Undefined behavior for -n */
}
produces this output on my system:
-2147483648
-2147483648
Operations on C unsigned types have more strictly defined behavior. This program:
#include <stdio.h>
#include <limits.h>
int main(void) {
unsigned int n = UINT_MAX / 2 + 1;
printf("%u\n%u\n", n, -n);
}
gives this output on a system with 32-bit int
(and no padding bits):
2147483648
2147483648
and will print two identical lines of output on any conforming implementation.
C++ has the same behavior (or undefined behavior) as C in this area.
In Perl, a large integer will fall over to a floating-point representation if it's too large to be represented as an integer -- but Perl scalars are complicated, and can simultaneously store more than one representation. On my 64-bit system, this Perl program:
#!/usr/bin/perl
use strict;
use warnings;
my $n = -2.0**63;
print $n, "\n", -$n, "\n";
printf "%d\n%d\n", $n, -$n;
gives this output:
-9.22337203685478e+18
9.22337203685478e+18
-9223372036854775808
-9223372036854775808
which I'm not entirely sure I can explain myself.
Python appears to fall back to some form of extended-precision integers, so the issue of overflow doesn't arise, and so there's no numeric value that is its own negation. A number of other languages (including, I think, most Lisp dialects) do the same thing.
In Ada, an integer overflow doesn't have undefined behavior; it's required to raise an exception. This program:
with Ada.Text_IO; use Ada.Text_IO;
procedure Foo is
N: Integer := Integer'First;
begin
Put_Line(Integer'Image(N));
Put_Line(Integer'Image(-N));
end Foo;
produces just one line of output:
-2147483648
and then dies with a Constraint_Error
exception.
And so on, and so on, and ....
So unless the instructor is just looking for zero as the answer, it depends very much on the context.
And looking at the question, why do you assume that 0
(which is a perfectly correct and obvious answer to the question as written, and apparently is the only correct answer in Java) isn't what the instructor was looking for?