Đề bài
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.
Ràng buộc
-10 ≤ base ≤ 10; 0 ≤ exponent ≤ 18
Ví dụ
Đầu vào:
base = 2
exponent = 10
Kết quả mong đợi:
expected = 1024
Đầu vào:
long long base = 2;
long long exponent = 10;
Kết quả mong đợi:
long long expected = 1024;
Đầu vào:
long base = 2;
long exponent = 10;
Kết quả mong đợi:
long expected = 1024;
Giải thích
2 multiplied by itself 10 times is 1024.
Đầu vào:
base = 5
exponent = 0
Kết quả mong đợi:
expected = 1
Đầu vào:
long long base = 5;
long long exponent = 0;
Kết quả mong đợi:
long long expected = 1;
Đầu vào:
long base = 5;
long exponent = 0;
Kết quả mong đợi:
long expected = 1;
Giải thích
Anything to the power 0 is 1.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
The exponent tells you how many times to keep multiplying the base into an accumulating result.
Gợi ý 2
Start from the neutral value for multiplication so the zero-exponent case works naturally.
Gợi ý 3
Watch for the edge case where the exponent is zero, since no looping should still give a valid answer.
Độ phức tạp mong đợi
O(exponent) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.