PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

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

 October 18, 2022     conditional-statements, function, javascript, logical-operators, recursion     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing