20. Computing mathematical absolute value for int/long and result overflow
Mathematical absolute value is notated by placing the value between two pipe operators and is computed as follows:
|x| = x, |-x| = x
It is commonly used for computing/expressing distances. For example, imagine that 0 represents the sea level and we have a scuba diver and a climber. The scuba diver is underwater at -45 ft (notice that we use negative numbers to express how deep in the water the scuba diver is). At the same time, the climber has climbed 30 ft high. Which of them is closer to the sea level (0)? We may think that since -45 < 30, the scuba diver is closer because its value is smaller. However, we can easily find the correct answer by applying the mathematical absolute, as follows:
|-45| = 45, |30| = 30
45 > 30, so the climber is closer to the sea level (0)
Now, let’s dive into the solution with the following example:
int x = -3;
int absofx = Math.abs(x); // 3
...