I came up with only one way:

if(x > 0) { x -= x*2; } else x -= x*-2; 

Is it possible without that if-else , in one line?

  • x -= Math.abs(x*2); - entithat
  • Does not fit: let's say x = -5: x = -5 - | -5 * 2 | = -15 - Anton Sorokin
  • why not fit? values ​​are the same as in your example, as in the example of @entithat - Aleksey Muratov
  • @AlekseyMuratov Yes, you are right. Fixed an example, now if x <0, it will be like this: x = -5 + 10; - Anton Sorokin
  • 2
    Hmm .. A -x does not allow to use Zarathustra? - MBo

3 answers 3

Everything is easier than it seems. x = -x; which is equivalent to x = -1 * x;

  • Oops, yes. It is strange that I did not think about it. - Anton Sorokin
  • I will even re-accept your answer, although I usually don’t do it - Anton Sorokin

Condition

 if (x > 0) { x -= x * 2; } else { x -= x * -2; } 

can be represented as:

 x -= x > 0 ? x * 2 : x * -2; 

or so:

 x -= x * ((x > 0) ? 2 : -2); 

    Condition

     if (x > 0) { x -= x * 2; } else { x -= x * -2; } 

    What about x = -x ?