Code Wars: Square Every Digit

Nilesh Saini
2 min readJul 24, 2021

--

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.

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

Photo by Dhruv on Unsplash

My approach to this problem is:

  1. To convert the integer passed in the function to a string.
  2. Create an array of all the items in the string using the split(‘’) method.
  3. Use the map method to square each item in the array and push it to a new array.
  4. Join the new array formed after using the map method using the join(‘’) method.
  5. Since the join(‘’) will return a string, convert that to integer and return.

Here’s my Code:

function squareDigits(num){
//may the code be with you
let number = '' + num;
let newNum = new Array();
number.split('').map(n => {
newNum.push(n**2);
})

return parseInt(newNum.join(''));
}

We can refactor this code:

function squareDigits(num){
//may the code be with you
let newNum = new Array();
('' + num).split('').map(n => {
newNum.push(n**2);
})

return parseInt(newNum.join(''));
}

Here are some more solutions with best practices:

// Solution 1
const squareDigits = num => parseInt(String(num).split('').map(x => parseInt(x)**2).reduce((a, x) => a + String(x)))
// Solution 2
function squareDigits(num){
return Number(String(num).split("").map(function (item) { return Math.pow(Number(item), 2); }).join(""));
}
// Solution 3
function squareDigits(num){
var res = "";
num = num.toString();
for (var i = 0; i < num.length; i++)
{
res = res + (num[i] * num[i]).toString();
}
return Number(res);
}
// Solution 4
squareDigits = num => +[...num+''].map(x=>x*x).join``
//Solution 5 - using regex
function squareDigits(num){
//may the code be with you
return parseInt(String(num).split('').map( x => Math.pow(x,2)).join().replace(/,/g,''))
}

Final Notes:

Thank you so much for reading!

If you did something different to solve this problem then comment your solution below.

--

--

Nilesh Saini
Nilesh Saini

Written by Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube

No responses yet