Tutte le sfide
Facile 0 risolte 0% di accettazione

Digit Sum of a Power of Two

Add up the decimal digits of 2 raised to the power n.

Cosa imparerai

  • Double a number stored as digits
  • Sum the digits of a large number
  • Handle the n = 0 case

Problema

Mostra traduzione

Powers of two grow fast: 2^64 already has 20 digits and 2^2000 has over 600. Compute 2^n exactly and add up its decimal digits. Without big integers, keep the number as an array of digits and double it n times.

Implement digit_sum_power_of_two(n).

Input

n: The exponent.

Output

Return the sum of the decimal digits of 2^n.

Vincoli

0 ≤ n ≤ 2000

Esempi

Esempio 1
Input:
n = 10

Output atteso:
expected = 7
Input:
long long n = 10;

Output atteso:
long long expected = 7;
Input:
long n = 10;

Output atteso:
long expected = 7;

Spiegazione

2^10 = 1024 and 1 + 0 + 2 + 4 = 7.

Esempio 2
Input:
n = 0

Output atteso:
expected = 1
Input:
long long n = 0;

Output atteso:
long long expected = 1;
Input:
long n = 0;

Output atteso:
long expected = 1;

Spiegazione

2^0 = 1, so the digit sum is 1.

Come affrontarlo

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

Suggerimento 1

2^n is 1 doubled n times.

Suggerimento 2

Store digits with the lowest digit first so carries move toward the end of the array.

Suggerimento 3

Add the digits only once the doubling is finished.

Complessità attesa

O(n²) time, O(n) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

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