문제
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
예시
입력:
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.
입력:
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