+ 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?

26th Sep 2018, 7:04 PM
Daniel Cooper
Daniel Cooper - avatar
6 Réponses
+ 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.
26th Sep 2018, 11:05 PM
Morpheus
Morpheus - avatar
+ 3
Or better way without output null checking, sure match method. var numZeros1 = prod.match(/0*$/)[0].length;
26th Sep 2018, 11:56 PM
Calviղ
Calviղ - avatar
+ 2
Try this var match = prod.match(/0+$/); var numZeros = match? match[0].length:0; https://code.sololearn.com/Ws6j0g6BDznH/?ref=app
26th Sep 2018, 11:32 PM
Calviղ
Calviղ - avatar
+ 2
Morpheus That's why I tried using regular expressions first. But I couldn't get it to work so I settled for what I have now. It works, but still wanted to figure out the best way. I'll try Calviղs way and your way.
27th Sep 2018, 5:01 AM
Daniel Cooper
Daniel Cooper - avatar
+ 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)
26th Sep 2018, 9:55 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Can I have an example of this? I initially wanted to use a regex but i'm awful at them. Lol.
26th Sep 2018, 10:20 PM
Daniel Cooper
Daniel Cooper - avatar