二分求幂算法

double powerWithUnsignedExponent(double base,unsigned int exponent)
{
	if(exponent==0)
		return 1;
	if(exponent==1)
		return base;
	double result=powerWithUnsignedExponent(base,exponent>>1);//exponent>>1即exponent/2 
	result*=result;
	if(exponent & 0x1==1)//a & 0x1相当于a%2 
		result*=base;
	return result;
}

 非递归:

int power(int a,int b)
{
	int ans=1;
	while(b!=0)
	{
		if(b%2==1)
			ans*=a;
		b/=2;
		a*=a;
	}
	return ans;
}

 

相关文章:

  • 2021-08-12
  • 2022-12-23
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-12
猜你喜欢
  • 2021-09-17
  • 2022-02-14
  • 2021-11-19
  • 2021-09-04
  • 2022-12-23
  • 2021-05-28
相关资源
相似解决方案