LeetCode:Pow(x, n)

简介:

要求

Implement pow(xn)

1. 特例

  • n=0, 直接返回1
  • n=1, 直接返回x
  • n<0,返回 1/pow(x,-n)

2. 优化

index = (n > 0 ? n : -n);
pow(x, index) = (index %2==1 ? pow(x, index/2)*x : pow(x, index/2));

 继续优化

pow(x, index) = (index %2==1 ? pow(x, index>>1)*x : pow(x, index>>1));

 

3. 参考代码

复制代码
 class Solution 
 {
    public:
    double pow(double x, int n) 
    {
        int index = n;
        if (n == 0)
            return 1;
        if (n == 1)
            return x;
        if (n < 0)
            index = -n;
        double rev = index%2==0 ? pow(x*x, index>>1) : pow(x*x, index>>1)*x;
        if (n < 0)
            return 1 / rev;
        else
            return rev;
    }
 };
复制代码

 



本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3766209.html,如需转载请自行联系原作者

相关文章
|
5月前
|
Java
Leetcode 372. Super Pow
真正的解法其实思路很简单,我随便举个例子就很容易理解了,假设要求(123^4567)%1337,只需要把这个幂式子分解成几个层次,然后把球模加到每一层中间就很容易计算出来了。
25 0
|
10月前
|
算法 安全 Swift
LeetCode - #50 Pow(x, n)
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
LeetCode 372. Super Pow
你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。
49 0
LeetCode 372. Super Pow
LeetCode 50. Pow(x, n)
实现pow(x,n),即计算x的n次方
61 0
LeetCode 50. Pow(x, n)
|
存储 机器学习/深度学习 算法
LeetCode 49字母异位词分组&50pow(x,n)&51八皇后
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
98 0
LeetCode 49字母异位词分组&50pow(x,n)&51八皇后
|
算法 Java C++
LeetCode(算法)- 50. Pow(x, n)
LeetCode(算法)- 50. Pow(x, n)
140 0
LeetCode(算法)- 50. Pow(x, n)
|
算法 Java Python
ACM 选手图解 LeetCode Pow(x,n)
ACM 选手图解 LeetCode Pow(x,n)
ACM 选手图解 LeetCode Pow(x,n)
|
算法 Serverless