What's the shortest way to inc or dec the absolute value of an int
but keep the signs (+
-
) ?
int a = 5;
int b = -7;
// increment abs of both
// a -> 6
// b -> -8
// incrementing 0 wasn't interesting me, I guess it can stay 0
(I'm sure it's not that hard but I will probably end up with some lines of code. But I wonder if I can make that very short, 1-liner ?). I also removed C# tag because this might be interesting for all kinds of languages.
IF 0 should be left as 0: since Math.Sign
returns +1, -1, or 0, you can do:
a += Math.Sign(a);
i'd imagine an in-line comparison is cheaper than an abs call:
int res = a + (a >= 0 ? 1:-1)
this assumes 0 is a positive number.
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