Solving 100 problems in JavaScript - Binary reversal
This is the first problem of "Solving 100 Problems in JavaScript" series. More problems will be solved in upcoming posts as a part of this series.
Given the function BinaryReversal(str) {}
take the str parameter being passed, which will be a positive integer, take its binary representation (padded to the nearest N * 8 bits) and reverse that string of bits. Finally return the new reversed string in decimal form.
For example: if str is "47" then the binary version of this integer is 101111
but we pad it to be 00101111
. Your program should reverse this binary string which then becomes: 11110100
and then finally return the decimal version of this string, which is 244
.
Some Other examples :
4567
==> 60296
213
==> 171
First lets break down the problem into steps and Figure out the assumptions.
str
will be a positive integer passed on as a string.
function BinaryReversal(str) {
// step 1
const binaryValue = Number(str).toString(2);
// step 2
const paddingLength = binaryValue.length % 8 === 0 ? 0 : 8 - binaryValue.length % 8
const paddedBinaryStr = [...Array(paddingLength).fill(0), ...binaryValue]
.join('');
// step 3
const ReversedBinaryStr = paddedBinaryStr.split('').reverse().join('');
// step 4
const reversedBinary2Decimal = parseInt(ReversedBinaryStr,2);
// step 5
return reversedBinary2Decimal;
}
function BinaryReversal(str) {
const binaryValue = Number(str).toString(2);
const paddingLength = binaryValue.length % 8 === 0 ? 0 : 8 - binaryValue.length % 8
const paddedReversedBinaryValue = [
...Array(paddingLength).fill(0),
...binaryValue]
.reverse()
.join('');
return parseInt(paddedReversedBinaryValue,2);
}
toString()
with no arguments just converts a number to its decimal equivalent, when given an argument it considers it to be the base to represent the resulting string. Example : .toString(2)
converts a Number to its binary representation.
Array(n).fill(0)
creates an array of n elements and initializes each value in the array to 0.
Most of you would think of using a loop to calculate the padding to the nearest N * 8 Bits (Step 2), but its not really necessary when you can take advantage of the newer JavaScript standards for cleaner/modern code.