Problème
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.
Contraintes
-10 ≤ base ≤ 10; 0 ≤ exponent ≤ 18
Exemples
Entrée :
base = 2
exponent = 10
Sortie attendue :
expected = 1024
Entrée :
long long base = 2;
long long exponent = 10;
Sortie attendue :
long long expected = 1024;
Entrée :
long base = 2;
long exponent = 10;
Sortie attendue :
long expected = 1024;
Explication
2 multiplied by itself 10 times is 1024.
Entrée :
base = 5
exponent = 0
Sortie attendue :
expected = 1
Entrée :
long long base = 5;
long long exponent = 0;
Sortie attendue :
long long expected = 1;
Entrée :
long base = 5;
long exponent = 0;
Sortie attendue :
long expected = 1;
Explication
Anything to the power 0 is 1.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
The exponent tells you how many times to keep multiplying the base into an accumulating result.
Indice 2
Start from the neutral value for multiplication so the zero-exponent case works naturally.
Indice 3
Watch for the edge case where the exponent is zero, since no looping should still give a valid answer.
Complexité attendue
O(exponent) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.