Tuesday, October 18, 2022

[FIXED] How to make a function which takes 5 and return 9, and takes 9 and return 5 without any logical and conditional operators like if-else and TO

Issue

I have tried this but I thought switch is also a conditional statement

    function cal(n){
      switch(n){
      case 5: 
        return 9;
        break;
      case 9:
        return 5;
        break;
     }
    }

Solution

This can be done with bitwise XOR ^

function fn(n) {
  return n ^ 0b1100;
}

console.log(fn(5));
console.log(fn(9));

a b a XOR b
0 0 0
1 0 1
0 1 1
1 1 0

The number 5 in decimal is 101 in binary, which means that

     101 
XOR 1101
--------
    1001 = (9 decimal)

The number 9 in decimal is 1001 in binary, which means that

    1001 
XOR 1101
--------
    0101 = (5 decimal)

0b1100 itself is just a numeric literal expressed in binary. It is equal to 12 in decimal, so n ^ 12 will work exactly the same way.



Answered By - VLAZ
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.