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

Spy Number

Check whether the sum of a number's digits equals the product of its digits.

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

  • Track a sum and a product in one pass
  • Start a product at 1 and a sum at 0
  • Notice how a 0 digit affects the product

โจทย์

ดูฉบับแปล

A spy number is a positive integer whose digit sum equals its digit product. For example, 1124 has sum 1 + 1 + 2 + 4 = 8 and product 1 × 1 × 2 × 4 = 8, so it is a spy number.

Implement spy_number(n).

Input

n: The number to test.

Output

Return true if the sum of the decimal digits of n equals their product, otherwise false. Every single-digit number is a spy number.

เงื่อนไข

1 ≤ n ≤ 10^18

ตัวอย่าง

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

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

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

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

คำอธิบาย

Sum 1 + 2 + 3 = 6 and product 1 × 2 × 3 = 6 are equal, so the answer is true.

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

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

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

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

คำอธิบาย

Sum 1 + 2 + 3 + 4 = 10 but product 1 × 2 × 3 × 4 = 24, so the answer is false.

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

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

คำใบ้ 1

Walk over the digits once and update both totals.

คำใบ้ 2

Start the product at 1, not 0.

คำใบ้ 3

Any number containing a 0 digit has product 0, so it cannot be spy unless the sum is 0 too.

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

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

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

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

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

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

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

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

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