Home > katas > Convert number to reversed array of digits (8kyu) [TypeScript]
Convert number to reversed array of digits (8kyu) [TypeScript]
Chek kata on Codewars
Description:
Given a random non-negative number, you have to return the digits of this number within an array in reverse order.
For example, 348597 => [7,9,5,8,4,3]
Ways to convert a number to a string and vice versa
toString() and parseInt()
String() and Number()
unary + operator
multiply by 1
Loop
export const digitize = (n: number): number[] => {
const answer = []
const str = n.toString()
for(const num of str){
answer.unshift(parseInt(num))
}
return answer
};
Array.from
export const digitize = (n: number): number[] => {
const str: string = String(n)
const convert = (el: string) => Number(el)
return Array.from([...str].reverse(), convert)
}
Let's make this solution a little bit shorter.
export const digitize = (n: number): number[] => {
return Array.from(String(n), Number).reverse()
}
Map
export const digitize = (n: number): number[] => {
return [...n.toString()].map(Number).reverse();
}