1469. Final Significant Digit

Hard7.5 points estimatedNumber TheoryMathsRecursion

A calculator display shows the factorial of n, that is 1 * 2 * 3 * ... * n, but a smudge hides all the trailing zeros, so the technician only cares about the last digit that is not zero. Given the integer n, return that digit of n!, where 0! is 1. For example 5! is 120, so the answer is 2. The factorial is far too large to build, so the answer has to come from the structure of factors of 2 and 5. Count how the digit repeats for each block of five and recurse on n divided by 5, for O(log n) time and O(1) space.

Example 1

Input:
n = 5
Output:
2
Explanation:

5! = 120, whose last non-zero digit is 2.

Example 2

Input:
n = 10
Output:
8
Explanation:

10! = 3628800, whose last non-zero digit is 8.

Example 3

Input:
n = 0
Output:
1
Explanation:

0! = 1, so the answer is 1.

Constraints

0 ≤ n ≤ 1015

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O(log n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…