How do I square a number's digits?

雨燕双飞 提交于 2019-12-10 12:13:34

问题


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

square(21){};

should result in 41 instead of 441


回答1:


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)



回答2:


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)




回答3:


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



回答4:


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



回答5:


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




回答6:


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



来源:https://stackoverflow.com/questions/30873116/how-do-i-square-a-numbers-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!