有趣的算法(持续更新)

返回二进制中1的个数

size_t countOf1(int num)
{
size_t count=0;
while(num)
{
num&=num-1;
++count;
}
return count;
}

返回比x大的2的幂级数:

int pow2gt (int x)	{	--x;	x|=x>>1;	x|=x>>2;	x|=x>>4;	x|=x>>8;	x|=x>>16;	return x+1;	}

时间复杂度为O(1)的浮点数开平方根算法:

float SqrtByCarmack( float number )
{
    int i;
    float x2, y;
    const float threehalfs = 1.5F;
    x2 = number * 0.5F;
    y  = number;
    i  = * ( int * ) &y;   
    i  = 0x5f375a86 - ( i >> 1 );
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );
    y  = y * ( threehalfs - ( x2 * y * y ) ); 
    y  = y * ( threehalfs - ( x2 * y * y ) );
    return number*y;
}

猜你喜欢

转载自blog.csdn.net/Sept_Lana/article/details/82812902