DEV Community

Discussion on: Daily Challenge #189 - Convert Number into Reversed Array

Collapse
 
aminnairi profile image
Amin • Edited

JavaScript

Assuming the input should be a positive integer as in the test cases.

Using modulo and division should make it an O(n) solution, n being the number of digits in the number.

We could also have used the toString method from the Number.prototype and then use a spread operator into an array, and then use the Array.prototype.reverse method to reverse each one of its digits, but that would have made the function run in O(n³) space I believe.

"use strict";

/**
 * @function
 * @name convertNtA
 * @summary Convert a number into an array of each digits reversed.
 * @param {number} number The number to convert.
 * @throws {Error} If the function is not called with exactly one argument.
 * @throws {TypeError} If the first argument is not a number
 * @throws {TypeError} If the first argument is not a number.
 * @throws {TypeError} If the first argument is lower than zero.
 * @return {number[]} The converted number.
 * @example
 * convertNtA(348597); // [7, 9, 5, 8, 4, 3]
 * convertNtA(6581554); // [4, 5, 5, 1, 8, 5, 6]
 * convertNtA(123456); // [6, 5, 4, 3, 2, 1]
 * convertNtA(987123); // [3, 2, 1, 7, 8, 9]
 *
 */
function convertNtA(number) {
    if (arguments.length !== 1) {
        throw new Error("Expected exactly one argument");
    }

    if (typeof number !== "number") {
        throw new TypeError("Expected first argument to be a number.");
    }

    if (number !== (number | 0)) {
        throw new TypeError("Expected first argument to be an integer.");
    }

    if (number < 0) {
        throw new RangeError("Expected first argument to be greater or equal to zero.");
    }

    const output = [];

    while (number !== 0) {
        const lastDigit = number % 10;

        output.push(lastDigit);

        number = number / 10 | 0;
    }

    return output;
}