读书人

怎么知道是2的几次方?不许用log函数

发布时间: 2012-09-21 15:47:26 作者: rapoo

如何知道是2的几次方?不许用log函数
我不想用多态,所以:

C/C++ code
typedef enum {    OGP_SHAPE_SPHERE = 1,    OGP_SHAPE_BOX = 1<<1,    OGP_SHAPE_CYLINDER = 1<<2,    OGP_SHAPE_CAPSULE = 1<<3,    OGP_SHAPE_CONVEX_HULL = 1<<4,    OGP_SHAPE_COMPLEX = 1<<5} ShapeType;

然后弄一个函数查找表:
C/C++ code
typedef void (*support_point_func)(const Shape& shape, const Vectorf& n, const Vectorf& result);void support_point_sphere(const Shape& shape, const Vectorf& n, const Vectorf& result);void support_point_box(const Shape& shape, const Vectorf& n, const Vectorf& result);void support_point_cylinder(const Shape& shape, const Vectorf& n, const Vectorf& result);void support_point_capsule(const Shape& shape, const Vectorf& n, const Vectorf& result);void support_point_convex_hull(const Shape& shape, const Vectorf& n, const Vectorf& result);void support_point_complex(const Shape& shape, const Vectorf& n, const Vectorf& result);class Shape {    unsigned char type;    static support_point_func support_point_func_table[];}

问题是,我的类型标签是用移位实现的(另外一个地方必须用这个),我如何知道那个值是2的多少次方?
如果用log()就没意思了,还不如直接switch(type)。

[解决办法]
C/C++ code
#include <iostream>using namespace std;int main(int argc,char* argv[]){    int num;    while(cin>>num, num != 0)    {        if((num&(num-1)) == 0)        {            for(int i = 0;;++i)            {                if(num == 1)                {                    cout<<"是2的"<<i<<"次方"<<endl;                    break;                }                else                {                    num >>= 1;                }            }        }        else        {            cout<<"不是2的整数次方"<<endl;        }    }}
[解决办法]
不断的除2就知道了。然后判断除数
[解决办法]
用位运算比较方便

2的整数次幂的特点
是2进制表示只有一个位置1,其他位都为0

因此,检查2进制表示是否只有一个位置为1
位置的序号就表示的乘方次数

可以建立一个表来方便的实现
[解决办法]
C/C++ code
/**    结果返回 -1 表示该数不是2的幂*/int check(int num){    int i;    int temp = 1;    int result;    bool flag = false;        for (i=0; i<32; i++)    {        if (temp & num)        {            if (flag)            {                return -1;            }            else            {                result = i;                flag = true;            }        }        temp = temp << 1;    }        return result;}
[解决办法]
C/C++ code
}int check(int n){    if(n <= 0 || n & (n-1))        return -1;    static int pow2mod37[37] = {/*0*/ -1,0,1,26,2, 23,27,-1,3,16,                                /*10*/24,30,28,11,-1, 13,4,7,17,-1,                                /*20*/25,22,-1,15,29, 10,12,6,-1,21,                                /*30*/14,9,5,20,8, 19,18};    return pow2mod37[n%37];} 

读书人网 >C++

热点推荐