ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Strong Number

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

สิ่งที่คุณจะได้เรียนรู้

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

โจทย์

ดูฉบับแปล

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.

เงื่อนไข

0 ≤ n ≤ 10^9

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
n = 145

ผลลัพธ์ที่คาดหวัง:
expected = True
อินพุต:
long long n = 145;

ผลลัพธ์ที่คาดหวัง:
bool expected = true;
อินพุต:
long n = 145;

ผลลัพธ์ที่คาดหวัง:
bool expected = true;

คำอธิบาย

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

ตัวอย่างที่ 2
อินพุต:
n = 123

ผลลัพธ์ที่คาดหวัง:
expected = False
อินพุต:
long long n = 123;

ผลลัพธ์ที่คาดหวัง:
bool expected = false;
อินพุต:
long n = 123;

ผลลัพธ์ที่คาดหวัง:
bool expected = false;

คำอธิบาย

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

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

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

คำใบ้ 2

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

คำใบ้ 3

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

ความซับซ้อนที่คาดหวัง

O(d) time for d digits, O(1) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก