How do I square a number's digits?

2.5k views Asked by At

How do I square a number's digits? e.g.:

square(21){};

should result in 41 instead of 441

6

There are 6 answers

0
vinayakj On BEST ANSWER

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)

1
Danny Delott On

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;
}

Use Math.pow to square numbers like this:

Math.pow(11,2); // returns 121

0
Maxqueue On

I think he means something like the following:

    var output = "";
    for(int i = 0; i<num.length; i++)
    {
        output.concat(Math.pow(num[i],2).toString());
    }
0
Adam On

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);
0
AudioBubble On

This is easily done with simple math. No need for the overhead of string processing.

var result = [];
var n = 21;
while (n > 0) {
    result.push(n%10 * n%10);
    n = Math.floor(n/10);
}

document.body.textContent = result.reverse().join("");

In a loop, while your number is greater than 0, it...

  • gets the remainder of dividing the number by 10 using the % operator

  • squares 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)

1
Andy On

Split the string into an array, return a map of the square of the element, and rejoin the resulting array back into a string.

function squareEachDigit(str) {
    return str.split('').map(function (el) {
        return (+el * +el);
    }).join('');
}

squareEachDigit('99') // 8181
squareEachDigit('52') // 254

DEMO