How do I programmatically return the maximum of two integers without using any comparison operators and without using if
, else
, etc?
The basic logic is simple, let's say we have two numbers a & b if a-b>0(i.e. the difference is positive) then a is maximum else if a-b==0 then both are equal and if a-b<0(i.e. diff is -ve) b is maximum.
If equals test in Python: if with == The equals ( == ) operator tests for equality. It returns True when both tested values are the same. When their values differ, the operator returns False .
To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).
max: // Will put MAX(a,b) into a
a -= b;
a &= (~a) >> 31;
a += b;
And:
int a, b;
min: // Will put MIN(a,b) into a
a -= b;
a &= a >> 31;
a += b;
from here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With