Solving 100 problems in JavaScript - Binary reversal

100JSprobs

Binary Reversal

Introduction

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.

The Video

The Problem

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

The Solution

First lets break down the problem into steps and Figure out the assumptions.

Assumptions -

str will be a positive integer passed on as a string.

Breakdown -

  1. Convert str to its equivalent binary representation.
  2. Pad it to the nearest N * 8 bits.
  3. Reverse the resulting string on step 2.
  4. Convert the string on step 3 to decimal.
  5. Return the resulting string.

Code -

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;

}

Optimized Code -

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

}

Notes -

  1. 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.

  2. Array(n).fill(0) creates an array of n elements and initializes each value in the array to 0.

  3. 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.