Pow(x, n)

Implement pow(xn).

class Solution {
public:
    double myPow(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 / (myPow(x,INT_MAX)*x);
            else
                return 1.0 / myPow(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-25 06:08:42

Pow(x, n)的相关文章

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

POW(x,y)

POW(x,y) 用于返回 x 的 y 次方的结果 mysql> SELECT POW(2,4), POW(2,-4); +----------+-----------+ | POW(2,4) | POW(2,-4) | +----------+-----------+ | 16 | 0.0625 | +----------+-----------+

[Leetcode]50. Pow(x, n)

Implement pow(x, n). #define EPSINON 0.00001 #define Max 2147483647 #define Min -2147483648 #define DBL_MAX 1.7976931348623159e+308 class Solution { public: double myPow(double x, int n) { /* three special case */ if(n==1) return x; if(n==0) return 1

[Math]Pow(x, n)

Total Accepted: 73922 Total Submissions: 269855 Difficulty: Medium Implement pow(x, n). (M) Sqrt(x) 1.递归 /* n = 0, <0 , >0 x = 0 ,x>0,x<0 */ class Solution { public: double myPowWithPositiveExp(double x,unsigned int n) { if(n==1){ return x; }

[LeetCode][JavaScript]Pow(x, n)

Pow(x, n) Implement pow(x, n). https://leetcode.com/problems/powx-n/ 注意x和n都可能是负数. 递归求解,比如求3的4次方,可以拆成3的2次方相乘:3的5次就是3^2相乘再乘2. 1 /** 2 * @param {number} x 3 * @param {number} n 4 * @return {number} 5 */ 6 var myPow = function(x, n) { 7 if(n >= 0){ 8 ret

LeetCode 050 Pow(x, n)

题目要求:Pow(x, n) Implement pow(x, n). 代码如下: class Solution { public: //采用二分法 //时间复杂度 O(logn),空间复杂度 O(1) double pow(double x, int n) { //要考虑n < 0的情况! if(n < 0) return 1.0 / power(x, -n); else return power(x, n); } double power(double x, int n){ if(n ==

[POI2007]洪水pow 题解

[POI2007]洪水pow 时间限制: 5 Sec  内存限制: 128 MB 题目描述 AKD市处在一个四面环山的谷地里.最近一场大暴雨引发了洪水,AKD市全被水淹没了.Blue Mary,AKD市的市长,召集了他的所有顾问(包括你)参加一个紧急会议.经过细致的商议之后,会议决定,调集若干巨型抽水机,将它们放在某些被水淹的区域,而后抽干洪水.你手头有一张AKD市的地图.这张地图是边长为m*n的矩形,被划分为m*n个1*1的小正方形.对于每个小正方形,地图上已经标注了它的海拔高度以及它是否是A

大数java(pow)

Problems involving the computation of exact values of very large magnitude and precision are common. For example, the computation of the national debt is a taxing experience for many computer systems. This problem requires that you write a program to

[LintCode] Pow(x, n) 求x的n次方

Implement pow(x, n). Notice You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than 1e-3. Have you met this question in a real interview? Yes Example Pow(2.1, 3)