求N!的二进制表示中最低位1的位置
编程之美是这样讲的
1 2 3 4 5 6 7 8 9 10 | int lowestOne(int N) { int Ret = 0; while(N) { N >>= 1; Ret += N; } return Ret; } |
我的想法比较简单,利用位左移作,比如1010,左移3次就变成0了,所以要求的最低位1的位置 = 4 – 3
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <stdio.h> #define INT_LENGTH (32) int main(void){ unsigned int n; int count = 0; scanf("%u", n); while(n){ n <<= 1; count++; } printf("last 1 position = %d\n", INT_LENGTH - count); return 0; } |
最新评论