Trung bình 2 đã giải Tỷ lệ chấp nhận 100.0%

Digit Power Sum

Add each digit raised to its position from the left.

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

  • Split a number into its digits from left to right
  • Raise each digit to a power that depends on its position
  • Accumulate a total inside a loop

Đề 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. For 352 that is 3¹ + 5² + 2³. A zero digit adds 0.

Implement digit_power_sum(n).

Input

n: A positive integer.

Output

Return the sum of the powered digits.

Ràng buộc

1 ≤ n ≤ 1,000,000,000

Ví dụ

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

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

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

Kết quả mong đợi:
long expected = 36;

Giải thích

3¹ + 5² + 2³ = 3 + 25 + 8 = 36.

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

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

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

Kết quả mong đợi:
long expected = 89;

Giải thích

8¹ + 9² = 8 + 81 = 89, the number itself.

Hướng tiếp cận

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

Gợi ý 1

Scan the number digit by digit from left to right and keep track of each digit’s position.

Gợi ý 2

Convert the number to a string or otherwise know the left-to-right index before combining each digit with its position.

Gợi ý 3

Remember that a zero digit contributes nothing, but its position still matters for the exponent count.

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

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

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.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 KKKaneki Ken Python 1,122 ms - 5/5 Xem code
2 JPJittipat Phonhan Go 1,486 ms - 4/5 Xem code

Học hỏi từ người khác

Giải pháp cộng đồng

Cảnh báo: Có 2 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem mã của người khác và đánh giá AI. Đăng nhập và giải thử thách để tham gia thảo luận.