leetcode(50)--求pow(x,y)

Implement pow(xn), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [−231, 231 − 1]

每天一练,leetcode第50题。求x的y次方。其实对于这种常常直接调用函数来解决的问题,自己做的时候才回感觉非常别扭,比如上次遇到求根号函数。(一道中等难度的题,大概费了我35分钟。。比之前手感都好一些了,看来刷题还是会有提升的。)

效率值仍然可以提升,自己能力也就这样了哈哈哈。

首先对这个问题思考,它不可能让你用一个for循环完成累乘,这样时间效率太低。于是可以细分指数,把指数进行二分,然后对相乘就可以减少运算次数。基于这个想法,有以下解法:

class Solution:
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        index = abs(n)
        if index == 0:
            return 1
        res = 1
        binary = bin(index).split('b')[-1]
        bit_width = len(binary)
        for i in range(bit_width):
            if binary[i] == '1':
                weight = bit_width - i - 1
                temp = x
                for j in range(weight):
                    temp *= temp
                res *= temp
        return res if n>0 else 1/res

猜你喜欢

转载自blog.csdn.net/leviopku/article/details/82835218