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

Digit Power Sum

Add each digit raised to its position from the left.

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

  • 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

โจทย์

ดูฉบับแปล

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.

เงื่อนไข

1 ≤ n ≤ 1,000,000,000

ตัวอย่าง

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

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

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

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

คำอธิบาย

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

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

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

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

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

คำอธิบาย

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

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

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

คำใบ้ 1

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

คำใบ้ 2

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

คำใบ้ 3

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

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

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

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

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

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