leetcode || 50、Pow(x, n)

problem:

Implement pow(x, n).

Hide Tags

Math Binary
Search

题意:求x的n次幂

thinking:

(1)最简单想到的是直观上的数学幂函数求法,測试通过。算法时间复杂度为O(n)

(2)依照标签提示,使用二分搜索法。

pow(x,n) = pow(x,n-n/2)*pow(x,n/2),每次对n的规模缩半,注意对n的奇偶进行讨论,算法时间复杂度为log(n)

(3)除了上述方法,这里还提到了一种十分巧妙而且高速的方法,原文描写叙述例如以下:

Consider the binary representation of n. For example, if it is "10001011", then x^n = x^(1+2+8+128) = x^1 * x^2 * x^8 * x^128. Thus, we don‘t want to loop n times to calculate x^n. To speed up, we loop through each bit, if the i-th bit is 1, then we add x^(1
<< i) to the result. Since (1 << i) is a power of 2, x^(1<<(i+1)) = square(x^(1<<i)). The loop executes for a maximum of log(n) times.

该方法通过扫描n的二进制表示形式里不同位置上的1,来计算x的幂次,最坏为O(n),但平均复杂度非常好

code:

(1)递归法:accepted

class Solution {
public:
    double pow(double x, int n) {
        double ret=1.0;
        if(x==1.0 )
            return 1.0;
        if(x==-1.0)
        {
            if(n%2==0)
                return 1.0;
            else
                return -1.0;
        }
        if(n<0)
            return 1.0/pow(x,-n);
        while(n)
        {
            if(ret==0) //防止执行超时
                return 0;
            ret*=x;
            n--;
        }
        return ret;
    }
};

(2)二分法:accepted

class Solution {
public:
    double pow(double x, int n) {
        //double ret=1.0;
        if(x==1.0 )
            return 1.0;
        if(x==-1.0)
        {
            if(n%2==0)
                return 1.0;
            else
                return -1.0;
        }
        if(n==0)
            return 1.0;
        if(n<0)
            return 1.0/pow(x,-n);
        double half=pow(x,n>>1);
        if(n%2==0)
            return half*half;
        else
            return x*half*half;
    }
};

(3)

为了正确计算x的n次幂,还须要考虑到下面一些情况:

1) x取值为0时。0的正数次幂是1,而负数次幂是没有意义的;推断x是否等于0不能直接用“==”。

2) 对于n取值INT_MIN时。-n并非INT_MAX。这时须要格外小心。

3) 尽量使用移位运算来取代除法运算,加快算法运行的速度。

class Solution {
public:
    double pow(double x, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n<0)
		{
			if(n==INT_MIN)
				return 1.0 / (pow(x,INT_MAX)*x);
			else
				return 1.0 / pow(x,-n);
		}
        if(n==0)
            return 1.0;
		double ans = 1.0 ;
		for(;n>0; x *= x, n>>=1)
		{
			if(n&1>0)
				ans *= x;
		}
		return ans;
    }
};
时间: 2024-10-21 02:07:23

leetcode || 50、Pow(x, n)的相关文章

【LeetCode 50】Pow(x, n)

Implement pow(x, n). 思路: 实现pow(x, n)函数.首先,可以n次连乘x,但是这样太慢了.加速:2^10 -> 4^5 -> 16^2 * 4 ->256^1 * 4 C++: 1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 5 if(0 == n) 6 return 1; 7 8 if(1 == n) 9 return x; 10 11 int index = n; 12 if(

leetcode || 118、Pascal&#39;s Triangle

problem: Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] Hide Tags Array 题意:帕斯卡三角形,又名杨辉三角形,是多项式(a+b)^n的系数 thinking: (1)杨辉三角形,从第三行开始,排除第一个和最后一个1外,其值

leetcode || 119、Pascal&#39;s Triangle II

problem: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? Hide Tags Array 题意:输出杨辉三角形的第K层 即:第K+1行 thinking: 题目要求使用O(K)的额外空间

LeetCode 50 Pow(x, n)(Math、Binary Search)(*)

翻译 实现pow(x, n). 原文 Implement pow(x, n). 分析 首先给大家推荐维基百科: zh.wikipedia.org/wiki/二元搜尋樹 en.wikipedia.org/wiki/Binary_search_tree 其次,大家也可以看看类似的一道题: LeetCode 69 Sqrt(x)(Math.Binary Search)(*) 然而这题我还是没有解出来,看看别人的解法-- class Solution { private: double myPowHel

LeetCode#50 Pow(x, n)

Just... Implement pow(x, n). Solution: 1)Naive solution:multiply x by itself for n-1 times. (Or simply reyurn 1 if n==0). This takes O(n) time. When n is big enough, it's relatively slow. 2)Fast Power. Take pow(3, 11) as an example. Here's what we're

leetCode 50.Pow(x, n) (x的n次方) 解题思路和方法

Pow(x, n) Implement pow(x, n). 思路:题目不算难,但是需要考虑的情况比较多. 具体代码如下: public class Solution { public double myPow(double x, int n) { boolean isMin0 = true;//结果负号 if(x > 0 || (n&1) == 0){//x>0或n为偶数 isMin0 = false;//为正 } x = x < 0 ? -x:x;//将x统一设为正值 dou

[LeetCode] 50. Pow(x, n) Java

题目: Implement pow(x, n). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 题意及分析:实现求x的n次方,使用分治法,复杂度降低到log2n 代码: public class Solution { public double myPow(double x, int n) { if(n < 0) return 1/pow(x,-n); e

leetcode 50 pow(x,y)

Implement pow(x, n), 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:

19.2.7 [LeetCode 50] Pow(x, n)

Implement pow(x, n), 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: