+ 2
Better ways of counting the zeros?
https://code.sololearn.com/Wm0CPovm9N4L/?ref=app (this code may not work with everyone) I was told there are better ways of counting the trailing zeros in this code. How?
6 Respuestas
+ 7
hi Daniel,
you were told most probably to look for alternative ways coz right now you are doing way more computation for the problem.
maintaining a number array,
multiply its values
converting result to string
finding trailing zeroes.
For this problem, the goal is just to find the power of 5 in n!, coz
5 * 2 is 10, and since 2 is abundant so 5 will decide the number of zeroes.
so find a algorithm to find 5's power in n!, thats the answer.
+ 3
Or better way without output null checking, sure match method.
var numZeros1 = prod.match(/0*$/)[0].length;
+ 2
Try this
var match = prod.match(/0+$/);
var numZeros = match? match[0].length:0;
https://code.sololearn.com/Ws6j0g6BDznH/?ref=app
+ 1
If you're comfortable with regex, you could use a regex to match just zeroes at the end of a string, using $ as a right-side anchor.
For example, if I wanted to match "earn":
"SoloLearn".match(/earn$/)
...then use .length on the answer to see how many characters were matched.
Since you want to match an arbitrary number of zeroes, you may to use special matchers (e.g.: */+ to repeat 0/1 or more occurrences of the previous token), but the $ as a pattern anchor would stay in the same spot.
If you go this route, make sure you handle the case where there is no match (null.length is a TypeError)
+ 1
Can I have an example of this?
I initially wanted to use a regex but i'm awful at them. Lol.