求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;
}
2009年12月21日 | 归档于 C
标签: ,
本文目前尚无任何评论.

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">