I saw a problem where we had to find the wage. If the hours are less than 40 we pay regular wage ($100/hr) if there is overtime we give 1.5 times the original pay ($150/hr).
The challenge was to solve it without if-else/loops/or ternary operations.
It was solved like this
int hours = /*some_number*/;
int wage = (100*hours) + (50*(hours-40))*(hours>40);
This code works.
(hours>40)
returns 1
if hours is greater than 40 and returns 0
if it is less.
I understand that it is some kind of boolean operation, but how does it work and what is this called exactly.
The right way to do it is straight-forward:
int hours = /*some_number*/;
int wage = 100*hours;
if (hours > 40) wage += 50 * (hours-40);
To squeeze it to a single expression, the example takes advantage of the fact that a boolean is either 1 or 0. So x*some_bool
evaluates to either x
or 0
.
In your case, if (hours > 40)
then
(50*(hours-40))*(hours>40) == (50*(hours-40)) * 1 == 50*(hours-40)
otherwise it is 0
.
(50*(hours-40))*(hours>40) == (50*(hours-40)) * 0 == 0
In general it is less readable to write code this way. The only valid uses IMO are in advanced algebraic transformations used in cryptography or complexity theory.