快速乘方
an = an/2*an/2 , n为even
an = a(n-1)/2*a(n-1)/2 *a , n为odd
double powerWithUnsignedExponent(double base, unsigned int exponent) { if(0 == exponent) return 1; if(1 == exponent) return base; double result = powerWithUnsignedExponent(base, exponnet >> 1); result *= result; if(1 == exponent & 0x1) //二进制末尾为1,一定是奇数 result *= base; return result; }
借助位运算判断奇偶性:
a & 0x1 == 0; //even偶数
a & 0x1 != 0; //odd奇数