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

Strong Number

Check whether a number equals the sum of the factorials of its digits.

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

  • Split a number into its digits with % and /
  • Precompute small factorials once
  • Compare a computed total with the original number

Đề bài

Xem bản dịch

A strong number is a number that equals the sum of the factorials of its digits. For example, 145 is strong because 1! + 4! + 5! = 1 + 24 + 120 = 145. Mathematicians call these numbers *factorions*; in base 10 there are only four of them, but your program should test the definition rather than a list.

Implement strong_number(n).

Use this definition: take each decimal digit d of n, add up d! for all of them (with 0! = 1), and compare the total with n. So 0 is not strong, because 0! = 1.

Input

n: The number to test.

Output

Return true if the sum of the factorials of the digits of n equals n, otherwise false.

Ràng buộc

0 ≤ n ≤ 10^9

Ví dụ

Ví dụ 1
Đầu vào:
n = 145

Kết quả mong đợi:
expected = True
Đầu vào:
long long n = 145;

Kết quả mong đợi:
bool expected = true;
Đầu vào:
long n = 145;

Kết quả mong đợi:
bool expected = true;

Giải thích

1! + 4! + 5! = 1 + 24 + 120 = 145, which is the number itself, so the answer is true.

Ví dụ 2
Đầu vào:
n = 123

Kết quả mong đợi:
expected = False
Đầu vào:
long long n = 123;

Kết quả mong đợi:
bool expected = false;
Đầu vào:
long n = 123;

Kết quả mong đợi:
bool expected = false;

Giải thích

1! + 2! + 3! = 1 + 2 + 6 = 9, and 9 ≠ 123, so the answer is false.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Keep a copy of n, because you will change the working value while taking digits off.

Gợi ý 2

Only the factorials of 0 to 9 are ever needed, so build them once.

Gợi ý 3

Check what your loop does when n is 0: it has one digit.

Độ phức tạp mong đợi

O(d) time for d digits, O(1) 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.