Problema
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.
Restrições
1 ≤ n ≤ 1,000,000,000
Exemplos
Entrada:
n = 352
Saída esperada:
expected = 36
Entrada:
long long n = 352;
Saída esperada:
long long expected = 36;
Entrada:
long n = 352;
Saída esperada:
long expected = 36;
Explicação
3¹ + 5² + 2³ = 3 + 25 + 8 = 36.
Entrada:
n = 89
Saída esperada:
expected = 89
Entrada:
long long n = 89;
Saída esperada:
long long expected = 89;
Entrada:
long n = 89;
Saída esperada:
long expected = 89;
Explicação
8¹ + 9² = 8 + 81 = 89, the number itself.
Como abordar
Tente sozinho primeiro e depois abra uma dica de cada vez.
Dica 1
Scan the number digit by digit from left to right and keep track of each digit’s position.
Dica 2
Convert the number to a string or otherwise know the left-to-right index before combining each digit with its position.
Dica 3
Remember that a zero digit contributes nothing, but its position still matters for the exponent count.
Complexidade esperada
O(d) time, O(1) extra space