uadafac31 uadafac31 - 4 months ago 23
Javascript Question

Trying to square every digit of a number, but my algorithm is not working?

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

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(""));
}
Comments