zoukankan      html  css  js  c++  java
  • [LeetCode] 50. Pow(x, n)

    题目链接 : https://leetcode-cn.com/problems/powx-n/

    题目描述:

    实现 pow(x, n) ,即计算 x 的 n 次幂函数。

    示例:

    示例 1:

    输入: 2.00000, 10
    输出: 1024.00000
    

    示例 2:

    输入: 2.10000, 3
    输出: 9.26100
    

    示例 3:

    输入: 2.00000, -2
    输出: 0.25000
    解释: 2-2 = 1/22 = 1/4 = 0.25
    

    说明:

    • -100.0 < x < 100.0
    • n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。

    思路:

    思路一:库函数

    思路二:倍降指数

    这道题有点像求解斐波那契数列,所以可以用递归和迭代的方法,如下面两种方法,

    class Solution:
        def myPow(self, x: float, n: int) -> float:
            if n < 0 : return self.myPow(1 / x, -n)
            if n == 0: return 1
            if n == 1:
                return x
            return x * self.myPow(x, n - 1)
    
    class Solution:
        def myPow(self, x: float, n: int) -> float:
            if n < 0:
                x = 1 / x
                n = -n
            if n == 0:
                return 1
            res = 1
            for _ in range(n):
                res *= x
            return res
    

    但是如果x = 1.00000,n = 2147483648,这就会超时,所以我们采用数学小技巧

    比如(2^{10} = {2^2}^5 = 4^5 = 4 ×{4^4} = 4 × 8^2 = ....)大家一定发现这里面小技巧了,我们可以通过不断缩小指数,来降低复杂度.


    关注我的的知乎专栏,了解更多的解题技巧,共同进步!

    代码:

    class Solution:
        def myPow(self, x: float, n: int) -> float:
            if n < 0 : return self.myPow(1 / x, -n)
            if n == 0: return 1
            if n % 2 == 0:
                return self.myPow(x*x, n//2)
            else:
                return x * self.myPow(x*x, n//2)
    
    class Solution {
        public double myPow(double x, int n) {
            if(n == 0)
                return 1;
            if(n<0){
                n = -n;
                x = 1/x;
            }
            if (n == Integer.MIN_VALUE)
                return myPow(x*x, -(n/2));
            return (n%2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
        }
    }
    
    class Solution:
        def myPow(self, x: float, n: int) -> float:
            if n < 0:
                x = 1 / x
                n = -n
            if n == 0:
                return 1
            res = 1
            while n :
                if n % 2 == 0:
                    n //= 2
                    x *= x
                else:
                    res *= x
                    n -= 1
            return res
    
  • 相关阅读:
    RabbitMq环境搭建
    Springboot集成quartz
    java8时间工具类
    AngularJS学习笔记之directive——scope选项与绑定策略
    理解$watch ,$apply 和 $digest --- 理解数据绑定过程
    AngularJS中service,factory,provider的区别
    AngularJS的Filter用法详解
    Angular.js中使用$watch监听模型变化
    history
    data-*
  • 原文地址:https://www.cnblogs.com/powercai/p/10882037.html
Copyright © 2011-2022 走看看