Reputation: 104702
I have an integer that needs its absolute value to be reduced by one.
Is there a shorter way than this:
if(number > 0) number--; else if (number < 0) number++;
Upvotes: 2
Views: 921
Reputation: 106630
Even shorter:
number -= Math.Sign(number);
Math.Sign
returns -1
, 0
, or 1
depending on the sign of the specified value.
Extension Method
Since you say you face this situation a lot it might be beneficial to make this an extension method to better express your intent:
public static int ReduceFromAbsoluteValue(this int number, int reduceValue)
{
return number - Math.Sign(number) * reduceValue;
}
4.ReduceFromAbsoluteValue(1); // 3
-4.ReduceFromAbsoluteValue(1); // -3
0.ReduceFromAbsoluteValue(1); // 0
Alternatively name this AddToAbsoluteValue
and change it to add the value.
Upvotes: 5
Reputation: 64904
Hack time!
return number - (number >> 31) + (-number >> 31);
x >> 31
will be -1 if x < 0
, 0 otherwise. So if number < 0
it will subtract -1 (add 1). If number > 0
then -number < 0
and it adds -1 if number > 0
. Both things are zero when number == 0
so it leaves that alone.
Upvotes: 2
Reputation: 1811
Slightly shorter:
number += number > 0 ? -1 : 1;
If all you need is the absolute value:
Math.Abs(number) - 1
Upvotes: 2