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)
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
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;
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
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.
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)