Problem
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.
Constraints
-10 ≤ base ≤ 10; 0 ≤ exponent ≤ 18
Examples
Input:
base = 2
exponent = 10
Expected output:
expected = 1024
Input:
long long base = 2;
long long exponent = 10;
Expected output:
long long expected = 1024;
Input:
long base = 2;
long exponent = 10;
Expected output:
long expected = 1024;
Explanation
2 multiplied by itself 10 times is 1024.
Input:
base = 5
exponent = 0
Expected output:
expected = 1
Input:
long long base = 5;
long long exponent = 0;
Expected output:
long long expected = 1;
Input:
long base = 5;
long exponent = 0;
Expected output:
long expected = 1;
Explanation
Anything to the power 0 is 1.
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
The exponent tells you how many times to keep multiplying the base into an accumulating result.
Hint 2
Start from the neutral value for multiplication so the zero-exponent case works naturally.
Hint 3
Watch for the edge case where the exponent is zero, since no looping should still give a valid answer.
Expected complexity
O(exponent) time, O(1) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.