Rendezvous interview question 2023-05-15

May 15, 2023


Write a function to find out whether the binary representation of a number is palindrome or not.

Example:

> binaryPal(5)
> true

> binaryPal(10)
> false

First, I convert the number to a string of base 2, then compare it to a reversed version of the string.

const binaryPal = (num) => {
const binary = Number(num).toString(2);
const binaryReverse = binary.split("").reverse().join("");
if (binary === binaryReverse) {
console.log(`${num} as binary: ${binary} => true`);
} else {
console.log(`${num} as binary: ${binary} => false`);
}
};

binaryPal(5);
binaryPal(10);
binaryPal(21);
binaryPal(100);
binaryPal(1000);
binaryPal(1001);

/*
5 as binary: 101 => true
10 as binary: 1010 => false
21 as binary: 10101 => true
100 as binary: 1100100 => false
1000 as binary: 1111101000 => false
1001 as binary: 1111101001 => false
*/