How to compute the integer absolute value without using if
condition. I guess we need to use some bitwise operation. Can anybody help?
The absolute value of an integer is its distance from zero on the number line. The absolute value of +3 is 3, and the absolute value of -3 is 3. Thus, opposite integers have the same absolute value. Mathematicians use the symbol || for absolute value.
Absolute value of an integer is its numerical value without taking the sign into consideration. The absolute values of -9 = 9; the absolute value of 5 = 5 and so on.
The absolute value of 5 is the distance of 5 from the 0. So you go 1, 2, 3, 4, 5. 5 is exactly 5 to the right of 0.
Same as existing answers, but with more explanations:
Let's assume a twos-complement number (as it's the usual case and you don't say otherwise) and let's assume 32-bit:
First, we perform an arithmetic right-shift by 31 bits. This shifts in all 1
s for a negative number or all 0
s for a positive one (but note that the actual >>
-operator's behaviour in C or C++ is implementation defined for negative numbers, but will usually also perform an arithmetic shift, but let's just assume pseudocode or actual hardware instructions, since it sounds like homework anyway):
mask = x >> 31;
So what we get is 111...111
(-1) for negative numbers and 000...000
(0) for positives
Now we XOR this with x
, getting the behaviour of a NOT for mask=111...111
(negative) and a no-op for mask=000...000
(positive):
x = x XOR mask;
And finally subtract our mask, which means +1 for negatives and +0/no-op for positives:
x = x - mask;
So for positives we perform an XOR with 0 and a subtraction of 0 and thus get the same number. And for negatives, we got (NOT x) + 1
, which is exactly -x
when using twos-complement representation.
Set the mask as right shift of integer by 31 (assuming integers are stored as two's-complement 32-bit values and that the right-shift operator does sign extension).
mask = n>>31
XOR the mask with number
mask ^ n
Subtract mask from result of step 2 and return the result.
(mask^n) - mask
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