โจทย์
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.
เงื่อนไข
-10 ≤ base ≤ 10; 0 ≤ exponent ≤ 18
ตัวอย่าง
อินพุต:
base = 2
exponent = 10
ผลลัพธ์ที่คาดหวัง:
expected = 1024
อินพุต:
long long base = 2;
long long exponent = 10;
ผลลัพธ์ที่คาดหวัง:
long long expected = 1024;
อินพุต:
long base = 2;
long exponent = 10;
ผลลัพธ์ที่คาดหวัง:
long expected = 1024;
คำอธิบาย
2 multiplied by itself 10 times is 1024.
อินพุต:
base = 5
exponent = 0
ผลลัพธ์ที่คาดหวัง:
expected = 1
อินพุต:
long long base = 5;
long long exponent = 0;
ผลลัพธ์ที่คาดหวัง:
long long expected = 1;
อินพุต:
long base = 5;
long exponent = 0;
ผลลัพธ์ที่คาดหวัง:
long expected = 1;
คำอธิบาย
Anything to the power 0 is 1.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
เลขชี้กำลังบอกว่าต้องคูณฐานเข้าไปในผลลัพธ์สะสมกี่ครั้ง
คำใบ้ 2
เริ่มจากค่าหน่วยของการคูณ เพื่อให้กรณีเลขชี้กำลังเป็นศูนย์ทำงานได้พอดี
คำใบ้ 3
ระวังเคสที่เลขชี้กำลังเป็นศูนย์ เพราะแม้ไม่วนลูปก็ยังต้องได้คำตอบที่ถูกต้อง
ความซับซ้อนที่คาดหวัง
เวลา O(exponent), หน่วยความจำเพิ่ม O(1)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน