Code Wars: Square Every Digit
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.
My approach to this problem is:
- To convert the integer passed in the function to a string.
- Create an array of all the items in the string using the split(‘’) method.
- Use the map method to square each item in the array and push it to a new array.
- Join the new array formed after using the map method using the join(‘’) method.
- 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.