This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions

1. Title Description

In this question comes from 1281

Second, train of thought analysis

N breaks down into bits, turns into numbers, adds up, multiplies.

AC code

I have five solutions, in order:

1. Reduce (

var subtractProductAndSum = function (n) {
    n = n.toString().split('');
    return n.reduce((x, y) => (x * y)) - n.reduce((x, y) => (+x) + (+y));
};
Copy the code

2. For traverses the string

var subtractProductAndSum = function(n) {
    let m = n.toString(10);
    let multi = 1;
    let sum = 0;
    for(let i=0; i<m.length; i++) {
        multi *= m[i];
        sum += m[i]*1;
    }
    return multi - sum;
};
Copy the code

ParseInt () string converts to a number

var subtractProductAndSum = function(n) {
    var str = n.toString();
    var sum = 0, total = 1;
    for(let i = 0 ; i< str.length ; i++){
        sum = sum + parseInt(str[i]);
        total = total * parseInt(str[i]);
    }
    return total - sum;
};
Copy the code

4. Convert to array or internal flavor

var subtractProductAndSum = function(n) {
    n = String(n).split("");
    let add = 0;
    let amass = 1;
    for(let i in n) {
        n[i] = parseInt(n[i]);
        add += n[i];
        amass *= n[i];
    }
    return amass - add;
};
Copy the code

5. While, mod, and math.floor ()

var subtractProductAndSum = function(n) {
  let sum = 0;
  let product = 1;
  while (n > 0) {
    digit = n % 10;
    sum += digit;
    product *= digit;
    n = Math.floor((n /= 10));
  }
  return product - sum;
};
Copy the code

Four,

After learning more about Reduce () recently, my first thought is reduce(). 2, 3, and 4 are routine operations.

Want to repeat 5: digital split type questions of the three kill: While, mod, and Math.floor do the mod to 10, and get the number at that position at each step. Use the Wihile loop until the end of the mod terminates the condition at the end of the mod. This depends on the problem and it’s best not to use parseInt(), if the number is too large or too small, you’ll get an error, The principle is that this function will convert the first argument to a string and then operate on it. The second argument has a different default value depending on the browser. Normally, we pass 10, which is decimal