Leecode Pow(x, n)实现任意次方函数

Pow(x, n)

Implement pow(x,n).

实现任意次方函数,注意:

1 n可以为正和负

2 x可以为正和负

下面使用二分法求解,不过因为两个的子解是一样的,所以可以只求一边解就可以了,这就是最典型的减治法了。

下面给出二分,三分,五分的求解程序:

double pow(double x, int n) {
		if (n == 0 || x == 1) return 1;
		if (x == 0) return 0;

		if (n < 0) x = 1/x;
		int a = abs(n);
		if (a == 1) return x;
		double t = pow(x, a/2);

		if (a%2 == 1)
			return x*t*t;

		return t*t;
	}


double pow3(double x, int n)
	{
		if (n == 0 || x == 1) return 1;
		if (x == 0) return 0;

		if (n < 0) x = 1/x;
		int a = abs(n);
		if (a == 1) return x;

		double t = pow3(x, a/3);
		double r = t*t*t;

		if (a%3 == 0) return r;
		if (a%3 == 1) return x*r;
		return x*x*r;
	}


double pow5(double x, int n)
	{
		if (n == 0 || x == 1) return 1;
		if (x == 0) return 0;

		if (n < 0) x = 1/x;
		int a = abs(n);
		if (a == 1) return x;
		//到了5不加这句会处理不了-1的特殊情况,出现答案错误。
		if (x == -1 && n%2 == 0) return 1;
		else if (x == -1) return -1;

		double t = pow5(x, a/5);
		double r = t*t*t*t*t;

		if (a%5 == 0) return r;
		if (a%5 == 1) return x*r;
		if (a%5 == 2) return x*x*r;
		if (a%5 == 3) return x*x*x*r;
		return x*x*x*x*r;
	}

下面是不用递归利用某些特性求解的,看下面注解:
http://discuss.leetcode.com/questions/228/powx-n

/*
Consider the binary representation of n. For example, if it is "10001011", then x^n = x^(1+2+8+128) = x^1 * x^2 * x^8 * x^128. Thus, we don't want to loop n times to calculate x^n. To speed up, we loop through each bit, if the i-th bit is 1, then we add x^(1 << i) to the result. Since (1 << i) is a power of 2, x^(1<<(i+1)) = square(x^(1<<i)). The loop executes for a maximum of log(n) times.
*/
double pow2(double x, int n) {
        unsigned m = abs((double)n);//这里不要用int,否则会溢出。
        double ret = 1;
        for ( ; m; x *= x, m >>= 1) {
            if (m & 1) { //m&1测试末位是否为1,是1就加上x,不是就不加。x是跟着移位不断平方
                ret *= x;
            }
        }
        return (n < 0) ? (1.0 / ret) : (ret);
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值