Converting numbers to base-7 representation in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Like the base−2 representation (binary), where we repeatedly divide the base 10 (decimal) numbers by 2, in the base 7 system we will repeatedly divide the number by 7 to find the binary representation.

We are required to write a JavaScript function that takes in any number and finds its base 7 representation.

For example −

base7(100) = 202

Example

The code for this will be −

const num = 100;
const base7 = (num = 0) => {
   let sign = num < 0 && '−' || '';
   num = num * (sign + 1);
   let result = '';
   while (num) {
      result = num % 7 + result;
      num = num / 7 ^ 0;
   };
   return sign + result || "0";
};
console.log(base7(num));

Output

And the output in the console will be −

202
raja
Published on 20-Nov-2020 17:52:36
Advertisements