DEV Community

Daily Challenge #189 - Convert Number into Reversed Array

dev.to staff on February 16, 2020

Setup Write a function that takes a random number as input and converts it into an array with the digits of that number appearing in rev...
Collapse
 
alvaromontoro profile image
Alvaro Montoro

A one liner in JavaScript:

const convertNtA = num => Number(num) && num >= 0 && (num+"").split("").reverse() || null;

It checks if it's a positive number, then turns it into a string, separate the characters and reverse them. If the parameter is not valid, it returns null.

Collapse
 
alvaromontoro profile image
Alvaro Montoro

This will process numbers that some people may not consider valid as they contain characters different than digits (e.g. 12e10).

Also having those && combined with || like that is not pretty... don't do it :P

Collapse
 
wheatup profile image
Hao

The result should be an array of numbers but this yields an array of strings.
Maybe consider adding .map(Number) after .reverse()?

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;
}
Collapse
 
vidit1999 profile image
Vidit Sarkar • Edited

C++

vector<int> convertNtA(long number){
    vector<int> numDigits;
    if(number == 0) // if number is zero then return vector with only 0
        return vector<int>({0});

    while(number > 0){
        numDigits.push_back(number%10);
        number /= 10;
    }
    return numDigits;
}

Python one liner

def convertNtA(number):
    return list(map(int,str(number)[::-1]))
print(convertNtA(123456))
convertNtA = lambda number : list(map(int,str(number)[::-1]))
print(convertNtA(123456))
Collapse
 
amcmillan01 profile image
Andrei McMillan

python

def convert_n_t_a(in_str):
    arr = list(in_str)
    arr.reverse()
    return arr

# --------------


print convert_n_t_a('348597')
print convert_n_t_a('6581554')
print convert_n_t_a('123456')
print convert_n_t_a('987123')
Collapse
 
nijeesh4all profile image
Nijeesh Joshy

dude, I don't think the input to the function is a string.

Collapse
 
qm3ster profile image
Mihail Malo

Whoops, looks like someone didn't specify the base of the number :o
How naughty!

function convertNtA(num, base = 10) {
  const len = Math.ceil(Math.log(num) / Math.log(base)),
    arr = Array(len)
  for (let i = 0; i < len; i++) {
    arr[i] = num % base
    num = (num / base) | 0
  }
  return arr
}
convertNtA(348597)
convertNtA(0x348597, 16)
Collapse
 
nijeesh4all profile image
Nijeesh Joshy • Edited

ruby


def convert_nt_a number
  number
    .to_s
    .split('')
    .reverse
    .map { |num| num.to_i }
end


# TESTS

require "test/unit"

class ConvertNtATest < Test::Unit::TestCase
  def test_convert_nt_a
    assert_equal [7,9,5,8,4,3],  convert_nt_a(348597)
    assert_equal [4, 5, 5, 1, 8, 5, 6],  convert_nt_a(6581554)
    assert_equal [6, 5, 4, 3, 2, 1],  convert_nt_a(123456)
    assert_equal [3, 2, 1, 7, 8, 9], convert_nt_a(987123)
  end
end

#1 tests, 4 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications


Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell:

convertNtA :: (Integral a) -> a -> [a]
convertNtA 0 = [] 
convertNtA n = n `mod` 10 : convertNtA (n `div` 10)
Collapse
 
savagepixie profile image
SavagePixie

Elixir one-liner:

def to_list_reverse(n), do: Integer.digits(n) |> Enum.reverse
Collapse
 
exts profile image
Lamonte

dart

List<int> reverseToArray(int number) {
  return number.toString().split("").reversed.map(int.parse).toList();
}
Collapse
 
jay profile image
Jay

Rust one liner:

fn convertNtA(num: i32) -> Vec<u32> {
    num.to_string()
        .chars()
        .map(|c| c.to_digit(10).unwrap())
        .rev()
        .collect()
}
Collapse
 
bkaguilar profile image
Bk Aguilar • Edited

In JavaScript


const converseNumber = n => Array.from(n.toString()).reverse().map(Number);