Suppose we have two inputs x and n. x is a number in range -100.0 to 100.0, and n is a 32-bit signed integer. We have to find x to the power n without using library functions.
So if the given inputs are x = 12.1, n = -2, then output will be 0.00683
To solve this, we will follow these steps −
Let us see the following implementation to get a better understanding −
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