Reputation: 86727
I have two numbers. I want the lower number to be the subtracted from both values.
x: 1000
y: 200
=> result: x = 800 and y = 0.
The following is kinda ugly to me, so is there a better approach I could do this?
if (x <= y) {
y = y - x;
x = 0
} else {
x = x - y;
y = 0;
}
Upvotes: 6
Views: 203
Reputation: 213223
How about this: -
int lower = x < y ? x : y;
x -= lower;
y -= lower;
Upvotes: 1
Reputation: 16905
As an addition to Duncan's answer, you can use this snippet if you only care about the value that is not going to be zero after the subtraction:
int non_zero = Math.abs(x - y); // unless the two are equal of course
Upvotes: 2
Reputation: 69339
This should do it:
int min = Math.min(x, y);
x -= min;
y -= min;
Upvotes: 11
Reputation: 13872
You can do following:
x = x - y;
y = 0;
if(x<0)
{
y = -x
x = 0;
}
Upvotes: 3