I was in a technical interview where the interviewer gave me a piece of code like this
int a=1;
a++;
...something..
...something.
if(a==25)
a=0;
he said me to rewrite this code without using switch,if else or ternary operator for the if condition. How it can be done?
i.e. you could just as easily write bool isSmall = i < 10; - it's this that avoids the if statement, not the separate function. Code of the form if (test) { x = true; } else { x = false; } or if (test) { return true; } else { return false; } is always silly; just use x = test or return test .
The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .
The conditional operator (or Ternary operator) is an alternative for 'if else statement'.
It's quite simple actually:
a *= (a != 25);
This will multiply a by 0 if a is equal to 25, else it will multiply a by 1.
If you're also not allowed to test for equality then here is a fully arithmetic way:
unsigned int v = a - 25;
/* test for bits set and put result in lsb of v */
v |= v >> 16;
v |= v >> 8;
v |= v >> 4;
v |= v >> 2;
v |= v >> 1;
/* set a to a if lsb of v is 1, else set to 0 */
a *= v & 1;
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