码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode][50] Pow(x, n)

时间:2018-09-18 22:54:19      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:方法   output   很多   x的n次方   math   not   new   int   ISE   

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:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [?231, 231 ? 1]

解析:

求指数函数,x的n次方。没做出来。。。- -

参考答案(别人写的)

public class Solution {
    public double MyPow(double x, int n) {
        double ans = 1;
        long absN = Math.Abs((long)n);
        while(absN > 0) {
            if((absN&1)==1) ans *= x;
            absN >>= 1;
            x *= x;
        }
        return n < 0 ?  1/ans : ans;
    }
}

代码很少,但是我感觉这个方法在很多地方都用到了,他这里是把一个整数分解成2进制数,比如:

9 = 2^3 + 2^0 = 1001
x^9 = x^(2^3) * x^(2^0)

先判断abs的二进制数低位有没有1,有的话就ans乘以x,没有的话就直接x乘以x,到最后肯定还是x乘以ans,每次循环absN都除2.类似于提取公因数2。比如:

14 = 2^3 + 2^2;
第一次循环: ans = 1; xNew = x^2; absN = 14;
第二次循环: ans = x^2; xNew = x^(2+2); absN = 7;
第三次循环: ans = x^(2+2+2); xNew = x^(2+2+2+2); abs = 3;
第四次循环: anx = x^(2+2+2+2+2+2+2); xNew = x^(2+2+2+2+2+2+2+2); abs=1;

每次循环就是遍历n的二进制的一位。

[leetcode][50] Pow(x, n)

标签:方法   output   很多   x的n次方   math   not   new   int   ISE   

原文地址:https://www.cnblogs.com/ekoeko/p/9671373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!