LeetCode 编程练习(50)

题目:

Implement pow(xn).


Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

实现代码:

#include <iostream>
using namespace std;

class Soulution {
public :
	double myPow(double x,int n)
	{
		if (n == 0)
			return 1.0;
		else if (n < 0)  //指数为负,只需要在分母上进行同样的运算
		{
			x = 1 / x;
			n = -1*n;
		}
		double result = 1;
		while (n > 0)  
		{
			if (n % 2 == 1)   //奇数次幂的情况多乘一个x
			{
				result = result*x;
			}
			n = n / 2;      
			x = x*x;      // x的n次等于x平方的二分之n次
		}
			return result;
	}
};

int main()
{
	Soulution a;
	cout<<a.myPow(2.1, 3)<<endl;
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/u013270326/article/details/78524494