How do I square a number's digits?

2019-06-10 20:17发布

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

square(21){};

should result in 41 instead of 441

6条回答
来,给爷笑一个
2楼-- · 2019-06-10 20:33

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);
查看更多
手持菜刀,她持情操
3楼-- · 2019-06-10 20:38

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)

查看更多
Juvenile、少年°
4楼-- · 2019-06-10 20:39

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

查看更多
老娘就宠你
5楼-- · 2019-06-10 20:45

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)

查看更多
Juvenile、少年°
6楼-- · 2019-06-10 20:48

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());
    }
查看更多
Bombasti
7楼-- · 2019-06-10 20:49

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

查看更多
登录 后发表回答