สมมติว่าเรามีอินพุตสองค่า x และ n x เป็นตัวเลขในช่วง -100.0 ถึง 100.0 และ n เป็น signed 32-bit integer เราต้องหา x^n โดยไม่ใช้ library functions
ตัวอย่าง x = 12.1, n = -2 ผลลัพธ์ 0.00683
ขั้นตอนการทำงาน (Binary Exponentiation / Fast Power)
power := |n|และres := 1.0- วนลูป
while power != 0:- ถ้าบิตสุดท้ายของ
powerเป็น 1 ให้res := res * x x := x * xpower >>= 1(หาร 2 / ขยับบิตขวา)
- ถ้าบิตสุดท้ายของ
- ถ้า
n < 0ให้คืน1 / res - คืนค่า
res
ตัวอย่างโค้ด (Python)
class Solution(object):
def myPow(self, x, n):
power = abs(n)
res = 1.0
while power:
if power & 1:
res *= x
x *= x
power >>= 1
if n < 0:
return 1 / res
return res
ob1 = Solution()
print(ob1.myPow(45, -2))
print(ob1.myPow(21, 3))
อินพุต
45 -2 21 3
เอาต์พุต
0.0004938271604938272 9261.0