Subtracting the smallest number from multiple numbers

I have two numbers. I want a smaller number to be subtracted from both values.

x: 1000 y: 200 => result: x = 800 and y = 0. 

It seems to me that I'm ugly, so could I do it better?

 if (x <= y) { y = y - x; x = 0 } else { x = x - y; y = 0; } 
+6
source share
5 answers

This should do it:

 int min = Math.min(x, y); x -= min; y -= min; 
+11
source

You can do the following:

 x = x - y; y = 0; if(x<0) { y = -x x = 0; } 
+3
source

As a complement to Duncan's answer, you can use this snippet if you only care about a value that will not be zero after subtraction:

 int non_zero = Math.abs(x - y); // unless the two are equal of course 
+2
source

What about: -

 int lower = x < y ? x : y; x -= lower; y -= lower; 
+1
source
 x=xy; y=yx; if(x<0) x=0; else y=0; 
0
source

All Articles