标签:
处理数值计算问题的两种方法:1、基于分治法的二进制分解的方法;2、基于减二法的二分法。参考Code Ganker。
基于分治法的二进制分解的方法
class Solution {
public:
double myPow(double x, int n) {
bool isNegative = false;
if(n % 2 == 1 && x < 0)
isNegative = true;
x = abs(x);
if(n < 0) {
x = 1 / x;
n = -n;
}
double result = 1.0;
while(n > 0) {
if(1 == (n & 1))
result *= x;
x *= x;
n = n >> 1;
}
return isNegative == false ? result : -result;
}
};
基于减二法的二分法
class Solution {
public:
double minusTwo(double x, int n) {
if(n == 1)
return x;
double result = minusTwo(x, n / 2);
if(1 == n % 2) {
result = result * result * x;
}else {
result = result * result;
}
return result;
}
double myPow(double x, int n) {
if(0 == n)
return 1.0;
bool isNegative = false;
if(n % 2 == 1 && x < 0)
isNegative = true;
x = abs(x);
if(n < 0) {
x = 1 / x;
if(-2147483648 == n)
n = 2147483647;
else
n = -n;
}
return true == isNegative ? -minusTwo(x, n) : minusTwo(x, n);
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/guanzhongshan/article/details/47042027