Fredou
Fredou

Reputation: 20100

checking if a number is even but not zero, in 1 condition?

I don't think it is possible but can this be done in 1 condition instead of 2?

I'm trying not to do this

bool test = (Number1 & 1) == 0 && (Number1 > 0);

or this

bool test = (Number1 & 1) == 0 && (Number1 != 0);

Upvotes: 0

Views: 525

Answers (2)

JML
JML

Reputation: 409

Will return true for all even numbers >= 2 and false for all odd numbers, as well as all numbers <= 0:

bool test = ((Number1 - 1) % 2 == 1);

Upvotes: 4

Corey Ogburn
Corey Ogburn

Reputation: 24717

Although this is technically putting Number1 into a variable, I think it'll work. I'm assuming Number1 is returned from a long running function call or property? Either way:

private bool IsEvenNotZero(int num) {
    return (num & 1) == 0 && (num != 0);
}

bool test = IsEvenNotZero(Number1);

This will put it in a parameter and you can test the parameter twice that way. I don't know why you can't put Number1 in a normal variable, and without knowing more about the situation I don't know if any better can be done.

Upvotes: 0

Related Questions