I believe this is what the OP is looking for? The square of each digit?
var number = 12354987,
var temp = 0;
for (var i = 0, len = sNumber.length; i < len; i += 1) {
temp = String(number).charAt(i);
output.push(Number(temp) * Number(temp));
}
console.log(output);
function sq(n){
var nos = (n + '').split('');
var res="";
for(i in nos){
res+= parseInt(nos[i]) * parseInt(nos[i]);
}
return parseInt(res);
}
var result = sq(21);
alert(result)
You'll want to split the numbers into their place values, then square them, then concatenate them back together. Here's how I would do it:
function fn(num){
var strArr = num.toString().split('');
var result = '';
for(var i = 0; i < strArr.length; i++){
result += Math.pow(strArr[i], 2) + '';
}
return +result;
}
I believe this is what the OP is looking for? The square of each digit?
Split the string into an array, return a
map
of the square of the element, and rejoin the resulting array back into a string.DEMO
This is easily done with simple math. No need for the overhead of string processing.
In a loop, while your number is greater than 0, it...
gets the remainder of dividing the number by
10
using the%
operatorsquares it and adds it to an array.
reduces the original number by dividing it by 10, dropping truncating to the right of the decimal, and reassigning it.
Then at the end it reverses and joins the array into the result string (which you can convert to a number if you wish)
I think he means something like the following:
You'll want to split the numbers into their place values, then square them, then concatenate them back together. Here's how I would do it:
Use Math.pow to square numbers like this:
Math.pow(11,2); // returns 121