uadafac31 - 1 year ago 65

Javascript Question

I'm trying to square every digit of a number;

for example:

123 should return 149

983 --> 81649 and so on

I messed it up somewhere in the following Javascript code and I'm looking for some guidance.

`function splitNumber(num){`

var arr = [];

while(num>0){

var c = num%10;

arr[arr.length]=c;

num=num/10;}

return arr;

}

function squareArrToNumber(arr){

var c = 0;

for(var i=arr.length-1;i>=0;i--){

arr[i]=arr[i]^2;

if(arr[i]^2>10)

c = c*100+arr[i];

else

c = c*10+arr[i];

}

return c;

}

function squareDigits(num){

squareArrToNumber(splitNumber(num));

}

Answer Source

Try out this code

```
function numToSqr(num){
var i, sqr=[],n;
num = num.toString();
for(i=0;i<num.length;i++){
n = Number(num[i]);
sqr.push(n*n);
}
return Number(sqr.join(""));
}
```