Leetcode-172-factorial zero

Time:2021-12-1

Factorial zero

Title Description: given an integer n, return n! The number of zeros in the mantissa of the result.

See leetcode’s official website for an example.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution 1: count the number of occurrences of 2 and 5

because2*5=10Therefore, as long as there is one 2 and 5, there will be one more 0. Therefore, the number of zeros can be obtained by counting the times that can be divided by 2 or 5. Use twocount to record the number of occurrences of 2 and fivecount to record the number of occurrences of 5. The specific methods are as follows:

  • Traverse the number num from 1 to N;
  • Calculate the number of times num can be divided by 2 or 5;
  • Finally, the smaller of twocount and fivecount is returned, that is, the final n! The number of zeros in the mantissa of the result.
public class LeetCode_172 {
    public static int trailingZeroes(int n) {
        int twoCount = 0, fiveCount = 0;
        for (int i = 1; i <= n; i++) {
            int num = i;
            while (num % 2 == 0 || num % 5 == 0) {
                if (num % 2 == 0) {
                    twoCount++;
                    num = num / 2;
                }
                if (num % 5 == 0) {
                    fiveCount++;
                    num = num / 5;
                }
            }
        }
        return Math.min(twoCount, fiveCount);
    }

    public static void main(String[] args) {
        System.out.println(trailingZeroes(5));
    }
}

[daily message]Keep your love, go to the mountains and seas, be loyal to yourself, love life, be content and progressive, live up to your ambition, and strive to meet each other at the peak.