Square Every Digit

Square Every Digit

This is a simple code wars kata I did today.

DESCRIPTION:

Welcome. In this kata, you are asked to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. (81-1-1-81)

Example #2: An input of 765 will/should return 493625 because 72 is 49, 62 is 36, and 52 is 25. (49-36-25)

Note: The function accepts an integer and returns an integer.

Happy Coding!

Solution:

I first had to get an array of digit from the passed parameter

const arrayOfDigits = num.toString().split('')

This turns the passed argument into an array.

I used the map function to square each digit in the already-formed array.

const map = arrayOfDigits.map((x) => x * x);
//alternatively
const map = arrayOfDigits.map((x) => Math.sqrt(x));

Place the digit back from an array to an interger.

const map = Number(map.join(""))

Combined the code should look like this.

function squareDigits(num){
  //turning the number to an array
  const arrayOfDigits = num.toString().split('')
  //squaring each digit of the created array
  const map = arrayOfDigits.map((x) => x * x);
  //joining back the result in number format
  const map1 = Number(map.join(""))
  return map1
}
console.log(squareDigits(543576))
//output expected
25169254936

Problem link: Kata's problem