In Mathematics, if you have a number X, then --X is always the same as X.

In Computers, this is not always the case. Here is an example. See if you can find the problem. The answer is hidden below.

Javascript

PHP

X

-X

123456789

-123456789

9223372036854775807

-9223372036854775807

-9223372036854775808

9.2233720368548E+18

Python

Java

C

Look carefully at the last Java row. Notice anything different about -X? How can -X = X when X is not zero?

Most computers use what is called "two's complement arithemetic".
Let's consider a computer with just 3 bits, but the same principle applies for 16, 32 or 64 bit computers.
In a three bit computer, only 2^{3} (8) values are possible.
So the only numbers available are -4 to 3, as shown here, in the first two columns.

Bits

Number

Flip Bits

Add 1

Negative

0 1 1

3

1 0 0

1 0 1

-3

0 1 0

2

1 0 1

1 1 0

-2

0 0 1

1

1 1 0

1 1 1

-1

0 0 0

0

1 1 1

0 0 0

0

1 1 1

-1

0 0 0

0 0 1

1

1 1 0

-2

0 0 1

0 1 0

2

1 0 1

-3

0 1 0

0 1 1

3

1 0 0

-4

0 1 1

1 0 0

-4

I think you can already start to see what the problem is. We can express -4, but not +4.

To take the negative of a number, the rule is "flip the bits and add 1".
In the last row, you can see that the negative of -4 is -4, which is clearly wrong.

In case you are wondering, " one's complement arithmetic" solves this problem nicely.
For a three bit computer, numbers range from -3 to 3, but there are two distinct zeros! 0 and -0. And they are not the same.