Converting numbers to base-7 representation in JavaScript



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
Updated on: 2020-11-20T13:23:03+05:30

748 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements