Wednesday, August 5, 2015

Calculate x to the power of n

Problem Description
Implement pow(x, n) where x is a float and n is an integer.

Solutions
Analysis: This problem is pretty simple. We can calculate it in O(n) time. But we can also easily do it in O(log n ) time.

I. Recursive Solution - O(log n)
class Solution:
    # @param {float} x
    # @param {integer} n
    # @return {float}
    def myPow(self, x, n):
        if n == 0: return 1
        result = self.myPow(x, n/2) if n>0 else self.myPow(1/x, -(n/2))
        return result * result * (x if n % 2 == 1 else 1)
II. Non-recursive Solution - O(log n) time - O(log n) space
This solution use one additional array, which is quite obvious.
class Solution:
    # @param {float} x
    # @param {integer} n
    # @return {float}
    def myPow(self, x, n):
        if n == 0: return 1
        result = 1
        a = []
        t = n if n>0 else -n
        
        while t > 0:
            a.append(t % 2)
            t = t >> 1
        for i in range(1,len(a)+1):
            result = result * result * (1 if a[-i] == 0 else x)
        
        if n <0 : result = 1.0 / result
        return result
III. Non-recursive Solution - O(log n) time - O(1) space
This is an improvement on the solution numbered II.
class Solution:
    # @param {float} x
    # @param {integer} n
    # @return {float}
    def myPow(self, x, n):
        if n == 0: return 1
        m = n
        if n < 0:
            m = -m
            x = 1/x
        
        result = 1
        while m > 0:
            
            if (m & 1) == 1:
                result *= x
            x *= x
            m >>=1
            
        return result  

No comments:

Post a Comment