Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Factorial Digit Sum

Add up the decimal digits of n factorial.

Bạn sẽ học được gì

  • Multiply a digit array by a small number
  • Sum the digits of a large number
  • Remember that 0! = 1

Đề bài

Xem bản dịch

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ụ

Ví dụ 1
Đầ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.

Ví dụ 2
Đầ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.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.