Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment absolute value of int preserving sign?

Tags:

int

binary

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.

like image 540
Bitterblue Avatar asked Dec 12 '13 16:12

Bitterblue


2 Answers

IF 0 should be left as 0: since Math.Sign returns +1, -1, or 0, you can do:

a += Math.Sign(a);
like image 161
odyss-jii Avatar answered Oct 29 '22 14:10

odyss-jii


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.

like image 38
kolosy Avatar answered Oct 29 '22 14:10

kolosy