Torna alle sfide
Media 0 risolte 0% di accettazione

Digit Power Sum

Add each digit raised to its position from the left.

Cosa imparerai

  • 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

Problema

Mostra traduzione

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.

Vincoli

1 ≤ n ≤ 1,000,000,000

Esempi

Esempio 1
Input:
n = 352

Output atteso:
expected = 36
Input:
long long n = 352;

Output atteso:
long long expected = 36;
Input:
long n = 352;

Output atteso:
long expected = 36;

Spiegazione

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

Esempio 2
Input:
n = 89

Output atteso:
expected = 89
Input:
long long n = 89;

Output atteso:
long long expected = 89;
Input:
long n = 89;

Output atteso:
long expected = 89;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.