最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

arrays - Multiplying individual digits in a number with each other in JavaScript - Stack Overflow

matteradmin2PV0评论

I'm trying to make a program that will take the digits in a number and multiply them with each other. So 583 would be 5*8*3 = 120.

Its not working as intended, its just returning the number that was put in.

How can I fix it?

Here's the code:

function persistence(num) {
  //code me
  numString = num.toString();
  numArray = numString.split().map(function(t) {
    return parseInt(t)
  });


  function reducer(theNumArray) {
    let sum = 1;
    for (var i = 0; i < theNumArray.length; i++) {
      sum = sum * theNumArray[i];

    }
    return sum;
  }
  newNum = reducer(numArray);

  console.log(newNum);
};

persistence(485);

I'm trying to make a program that will take the digits in a number and multiply them with each other. So 583 would be 5*8*3 = 120.

Its not working as intended, its just returning the number that was put in.

How can I fix it?

Here's the code:

function persistence(num) {
  //code me
  numString = num.toString();
  numArray = numString.split().map(function(t) {
    return parseInt(t)
  });


  function reducer(theNumArray) {
    let sum = 1;
    for (var i = 0; i < theNumArray.length; i++) {
      sum = sum * theNumArray[i];

    }
    return sum;
  }
  newNum = reducer(numArray);

  console.log(newNum);
};

persistence(485);

Share Improve this question edited Apr 9, 2018 at 17:50 CRice 32.3k5 gold badges61 silver badges73 bronze badges asked Apr 9, 2018 at 17:46 user3148057user3148057 1211 silver badge4 bronze badges 3
  • 2 "485".split() === [ "485" ] – Hunter McMillen Commented Apr 9, 2018 at 17:52
  • What does your step debugger tell you? – user177800 Commented Apr 9, 2018 at 18:01
  • Possible duplicate of What is a debugger and how can it help me diagnose problems? – user177800 Commented Apr 9, 2018 at 18:02
Add a ment  | 

5 Answers 5

Reset to default 6

You could split the string with an empty string, for getting single digits. Then covert, if required all strings to a number.

function reducer(theNumArray) {
    var i, sum = 1;
    for (i = 0; i < theNumArray.length; i++) {
        sum *= theNumArray[i];
    }
    return sum;
}

function persistence(num) {
    var numArray = num.toString().split('').map(Number);
    return reducer(numArray);
}

console.log(persistence(485));

A shorter approach could be just taking the single digits by using a spread syntax with an iterator for strings, then just multiply the values and return the result.

function persistence(number) {
    return [...number.toString()].reduce((p, v) => p * v);
}

console.log(persistence(485));

You just need to change inside split('')

DEMO

function persistence(num) {
  //code me
  numString = num.toString();
  numArray = numString.split('').map(function(t) {
    return parseInt(t)
  });

  function reducer(theNumArray) {
    let sum = 1;
    for (var i = 0; i < theNumArray.length; i++) {
      sum = sum * theNumArray[i];

    }
    return sum;
  }
  newNum = reducer(numArray);

  console.log(newNum);
};

persistence(485);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can also use reduce method for array.

ES5

function persistence(num) {
  let result = num.toString().split('').reduce(function(total, v) {
    return total * v
  }, 1);
  console.log(result);
};

persistence(485);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6

It Can be more easy with Spread_syntax of ES6.

function persistence(num) {
  let result = [...num.toString()].reduce((total, v) => total * v, 1);
  console.log(result);
};

persistence(485);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You don't need to split the string you can just reference the chars by their number. This seems to work fine example for 4*8*5= 160.

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

function persistence(num) {
  numString = num.toString();
  let sum = 1;
  for (var i = 0; i < numString.length; i++) {
    sum = sum * numString[i];
  }
  console.log(sum);
};
persistence(485);

according to this the split method will have different results based on the inputs (obvious right?):

No Separator-> If you don't pass a separator argument to the split method, the resulting array will have a single element consisting of the entire string

so, basically from here:

numString.split()

you will get an array with the string (your number) inside of it, this should be changed to:

numString.split('')

so your whole code should be like this:

 function persistence(num) {
    numString = num.toString();
    numArray = numString.split().map(function(t) {
       return parseInt(t)
    });


 function reducer(theNumArray) {
     let sum = 1;
     for (var i = 0; i < theNumArray.length; i++) {
         sum = sum * theNumArray[i];
     }
     return sum;
 }
 newNum = reducer(numArray);

 console.log(newNum);
};

persistence(485);

Assuming num is a positive integer:

    function persistence(num) {
    var ans=1;    
    while( num!==0){
            ans=ans*(num-Math.floor(num/10)*10);
            num=Math.floor(num/10);

        }
        console.log(ans);
    }

    persistence(123);

This is based on (num-Math.floor(num/10)*10) extracting the least significant digit. For example

123 - Math.floor(123/10)*10

123 - 12*10

123 - 120

3

And so on after reducing num by one digits by integer divide by 10. You don't need strings.

Post a comment

comment list (0)

  1. No comments so far