membersound
membersound

Reputation: 86727

Subtracting lowest number from several numbers

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

Answers (5)

Rohit Jain
Rohit Jain

Reputation: 213223

How about this: -

int lower = x < y ? x : y;
x -= lower;
y -= lower;

Upvotes: 1

phant0m
phant0m

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

harry4
harry4

Reputation: 189

x=x-y;
y=y-x;
if(x<0)
    x=0;
else
    y=0;

Upvotes: 0

Duncan Jones
Duncan Jones

Reputation: 69339

This should do it:

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

Upvotes: 11

Azodious
Azodious

Reputation: 13872

You can do following:

x = x - y;
y = 0;

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

Upvotes: 3

Related Questions