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

    Implement pow(xn).

    求x的n次幂,如果用n个循环相乘,那就太简单了,肯定不是这题要考察的。

    解法:利用性质:

    n是奇数,n % 2 == 1, x^n = x^(n/2) * x^(n/2) * x;
    n是偶数,n % 2 == 0, x^n = x^(n/2) * x^(n/2);

    每次n/2,递归到下一层,直到n=0是返回1。 如果n为负数,利用x^-n = 1/x^n。

    Java:

    class Solution {
        public double myPow(double x, int n) {  
            if(n < 0)  
                return 1 / pow(x, -n);  
            else  
                return pow(x, n);  
        }
    
        public double pow(double x, int n){  
            if(n == 0)  return 1;  
            double mid=pow(x, n / 2);  
            if((n & 1) == 0)  
                return mid * mid;  
            else  
                return mid * mid * x;  
        }  
    }
    

    Python: Recursion, T: O(logn), S: O(logn)

    class Solution(object):
        def myPow(self, x, n):
            if n < 0 and n != -n:
                return 1.0 / self.myPow(x, -n)
            if n == 0:
                return 1
            v = self.myPow(x, n / 2)
            if n % 2 == 0:
                return v * v
            else:
                return v * v * x
    

    Python: Iteration, T: O(logn), S: O(1)

    class Solution(object):
        def myPow(self, x, n):
            """
            :type x: float
            :type n: int
            :rtype: float
            """
            result = 1
            abs_n = abs(n)
            while abs_n:
                if abs_n & 1:
                    result *= x
                abs_n >>= 1
                x *= x
    
            return 1 / result if n < 0 else result
    

    C++:

    class Solution {
    public:
        double myPow(double x, int n) {
            if (n < 0) return 1 / power(x, -n);
            return power(x, n);
        }
        double power(double x, int n) {
            if (n == 0) return 1;
            double half = power(x, n / 2);
            if (n % 2 == 0) return half * half;
            return x * half * half;
        }
    };
    

     

    类似题目:

    [LeetCode] 69. Sqrt(x) 求平方根

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    PCA本质和SVD
    特征工程(转载)
    python入门基础代码
    长尾理论
    金融行业数据分析
    [rancher-net]
    rancher中使用ingress-lbs做负载均衡
    python 高级语言特性
    docker从初识到深入
    关于容器技术的发展以及虚拟化技术的总结
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8555575.html
Copyright © 2011-2022 走看看