In a course on algorithms and data structures at my university, I received this question:
Which integer has the same bit-pattern as his negative value?
Means: x == -x
I know that 0 works, but I suspect that the instructor was looking for some other number x. What x is it? How would you find it?
Non-zero integers implies integers other than zero. Therefore, (...... −4,−3,−2,−1) − 4 , − 3 , − 2 , − 1 ) and (1,2,3,4.....) ( 1 , 2 , 3 , 4..... ) are non-zero integers.
The nonzero integers are [rational] integers other than zero, and thus have positive absolute value; they may be positive or negative numbers.
Answer: The absolute value of a non zero integer is always positive.
The opposite of any nonzero integer will be the same distance from 0 in the opposite direction. How do you know the opposite of a nonzero integer? A diver is 19 meters below the surface of the water. Use an integer to represent how far the diver will need to travel to reach the surface.
Integer.MIN_VALUE and Long.MIN_VALUE have no equivalent positive value and when you take the negative value of these, you get the same value.
Negative is the same as flipping all the bits and adding one. i.e.
-x = ~x + 1
So -0x80000000 = 0x7fffffff + 1 = 0x8000000
Note: Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE which is negative. This is outlined in the javadoc for this method.
Technically there are many answers and types
byte x = 0; short x = 0; char x = 0; int x = 0; int x = Integer.MIN_VALUE; float x = 0.0f; float x = -0.0f; long x = 0; long x = Long.MIN_VALUE; double x = 0.0; double x = -0.0; Byte x = 0; Short x = 0; Character x = 0; Integer x = 0; Integer x = Integer.MIN_VALUE; Float x = 0.0f; Float x = -0.0f; Long x = 0L; Long x = Long.MIN_VALUE; Double x = 0.0; Double x = -0.0;
A similar Java Puzzler is; when is the following expression true
.
x != x + 0
EDIT: Floating point has both +0.0
and -0.0
. A such you might consider -0.0
a different value to 0.0
although it is the case that -0.0 == -(-0.0)
Note: Double.compare(0.0, -0.0) > 0
Note:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With