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

Spy Number

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

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

  • 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

Đề bài

Xem bản dịch

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.

Ràng buộc

1 ≤ n ≤ 10^18

Ví dụ

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

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

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

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

Giải thích

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

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

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

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

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

Giải thích

Sum 1 + 2 + 3 + 4 = 10 but product 1 × 2 × 3 × 4 = 24, 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

Walk over the digits once and update both totals.

Gợi ý 2

Start the product at 1, not 0.

Gợi ý 3

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

Độ 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.