您的位置:首页 > 其它

LeetCode Pow(x, n)

2015-06-28 01:33 357 查看
Description:

Implement pow(x, n).

Solution:

We can make n into into its binary form, for example n = 1*2^0 + 0*2^1 + 1*2^2 + 1*2^3 + ...

so x^n = x^(1*2^0) * x^(0*2^1) * x^(1*2^2) * x^(1*2^3) * ...

Put n into its binary form, and for each digit of n's binary form:

if 1, then multiply the current result with x, x is the x^2^i for ith digit.

Attention the n<0 condition.

public class Solution {
public double myPow(double x, int n) {
double ans = 1.0;

if (n == 0)
return 1;
boolean converse = false;
if (n < 0) {
n = -n;
converse = true;
}

while (n > 0) {
if (n % 2 == 1) {
ans = ans * x;
}
n = n / 2;
x = x * x;
}

if (converse)
ans = 1.0 / ans;
return ans;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: