DEV Community

Cover image for Road to Genius: advanced #46
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: advanced #46

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

function POF(num) {
  if (num === 1)
    return true;
  if (num < 4)
    return false;
  if ((num & num - πŸ’°) !== 0)
    return false;
  return (num & 1431655765) === πŸ’Ž;
}
let A = POF(356);

// πŸ’° = ? (number)
// πŸ’Ž = ? (identifier)
// such that A = false (boolean)
Enter fullscreen mode Exit fullscreen mode

In today's challenge we need to fix two bugs, in what seems to be quite complex code. Especially if you've never worked with binary operations, but fear not.

The & operator is a binary and, it works like this:

This is purely mathematical (not javascript)
The and-operation returns 1 if both values are 1,
and returns 0 if any of the values is 0.
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0

Example:
x     = 1010
y     = 1100
x & y = 1000
Enter fullscreen mode Exit fullscreen mode

We need to ensure that the output from the function POF(356) is false. The first two if-conditions we can ignore because they won't give us any false return value. But the third might:

if ((num & num - πŸ’°) !== 0)
  return false;
Enter fullscreen mode Exit fullscreen mode

With num as 356, let's have a look at the possible choices for πŸ’°: 0, 1 and 356 itself. If we can use any of these to ensure that the if-condition returns false, then we've solved it, so let's try:

356 in binary is: 101100100

let πŸ’° = 0
-->  101100100 & 101100100 !== 0

let πŸ’° = 1
-->  101100100 & 101100011 !== 0

let πŸ’° = 356
-->  101100100 & 0 == 0
Enter fullscreen mode Exit fullscreen mode

The answer for πŸ’° should either be 0 or 1 (but not 356) to ensure the function returns right there. The final bug πŸ’Ž can be anything as long as we respect the previous sentence.

coding challenge answer

By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Get started and become a certified Codr today at https://nevolin.be/codr/

Top comments (0)