Joseph环,这次模固定是2.假设不是固定模2,那么一般时间效率是O(n)。可是这次由于固定模2,那么能够利用2的特殊性,把时间效率提高到O(1)。
规律能够看下图:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2VuZGVuMjM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
具体具体解析请看大师Knuth的Concrete mathematics。
补上纯粹利用位运算写的程序:
作者:靖心 http://blog.csdn.net/kenden23/article/details/30232645
int substraHighBit(int y)
{
int x = y;
x = x | (x>>1);
x = x | (x>>2);
x = x | (x>>4);
x = x | (x>>8);
x = x | (x>>16);
return y & (x >> 1);
} #include <cstdio>
int main()
{
int xy, z;
char e;
while (scanf("%d %c %d", &xy, &e, &z) && xy)
{
while (z--) xy = (xy << 3) + (xy << 1);
printf("%d\n", substraHighBit(xy) << 1 | 1);
}
return 0;
}