Đề bài
n! = 1 × 2 × ... × n grows faster than any power: 25! already has 26 digits. Compute n! exactly and add up its digits. Without big integers, store the number as an array of digits and multiply it by 2, 3, ..., n in turn.
Implement factorial_digit_sum(n).
Input
n: The number whose factorial is taken.
Output
Return the sum of the decimal digits of n!. Note that 0! = 1.
Ràng buộc
0 ≤ n ≤ 1000
Ví dụ
Đầu vào:
n = 5
Kết quả mong đợi:
expected = 3
Đầu vào:
long long n = 5;
Kết quả mong đợi:
long long expected = 3;
Đầu vào:
long n = 5;
Kết quả mong đợi:
long expected = 3;
Giải thích
5! = 120 and 1 + 2 + 0 = 3.
Đầu vào:
n = 0
Kết quả mong đợi:
expected = 1
Đầu vào:
long long n = 0;
Kết quả mong đợi:
long long expected = 1;
Đầu vào:
long n = 0;
Kết quả mong đợi:
long expected = 1;
Giải thích
0! is 1 by definition, so the answer is 1.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Start from 1 and multiply by 2, 3, ..., n.
Gợi ý 2
Multiply each digit, add the carry, keep the last digit and carry the rest.
Gợi ý 3
When the carry is still left over at the end, it becomes new digits.
Độ phức tạp mong đợi
O(n × D) time where D is the digit count of n!, O(D) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.