中級 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 つずつ開いてみましょう。

ヒント 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

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。