Problema
Compute base to the power exponent by multiplying base by itself exponent times in a loop. Any number to the power 0 is 1.
Implement power(base, exponent).
Input
base: The base. exponent: The exponent (zero or positive).
Output
Return base raised to exponent.
Vincoli
-10 ≤ base ≤ 10; 0 ≤ exponent ≤ 18
Esempi
Input:
base = 2
exponent = 10
Output atteso:
expected = 1024
Input:
long long base = 2;
long long exponent = 10;
Output atteso:
long long expected = 1024;
Input:
long base = 2;
long exponent = 10;
Output atteso:
long expected = 1024;
Spiegazione
2 multiplied by itself 10 times is 1024.
Input:
base = 5
exponent = 0
Output atteso:
expected = 1
Input:
long long base = 5;
long long exponent = 0;
Output atteso:
long long expected = 1;
Input:
long base = 5;
long exponent = 0;
Output atteso:
long expected = 1;
Spiegazione
Anything to the power 0 is 1.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
The exponent tells you how many times to keep multiplying the base into an accumulating result.
Suggerimento 2
Start from the neutral value for multiplication so the zero-exponent case works naturally.
Suggerimento 3
Watch for the edge case where the exponent is zero, since no looping should still give a valid answer.
Complessità attesa
O(exponent) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.