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

Disarium Number

Check whether a number equals the sum of its digits raised to their positions.

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

  • Read digits from left to right
  • Raise a digit to its position with integer arithmetic
  • Add powers without overflow

Đề bài

Xem bản dịch

Number the digits of n from the left starting at 1, raise each digit to the power of its position, and add the results. If the total is n itself, the number is a disarium number. For example, 175 gives 1¹ + 7² + 5³ = 1 + 49 + 125 = 175.

Implement disarium_number(n).

Input

n: The number to test.

Output

Return true if n is a disarium number, otherwise false. Every single-digit number is a disarium number.

Ràng buộc

1 ≤ n ≤ 10^9

Ví dụ

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

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

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

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

Giải thích

8¹ + 9² = 8 + 81 = 89, so the answer is true.

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

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

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

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

Giải thích

9¹ + 8² = 9 + 64 = 73, not 98, 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

Positions count from the left, so either turn n into a string or count the digits first.

Gợi ý 2

Use integer multiplication for powers instead of a floating point function.

Gợi ý 3

The largest term is 9^10, which fits easily in 64 bits.

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

O(d^2) 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.