标签:
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6996 Accepted Submission(s): 4138
#include "stdio.h" int getMax(int n) { int i=0,sum=0,t=1; for (i = 0; i < n; ++i) { if(i==0) t=1; else t*=2; sum+=t; } return sum; } int getMin(int n) { int i,t=1; for (i = 1; i < n; ++i) t*=2; return t; } int main() { int n,m,max,min,t,num,sum; while(scanf("%d",&n)!=-1) { while(n--) { scanf("%d",&m); max=getMax(m); min=getMin(m); sum=0; while(min<=max) { t=min; num=m; while(num--) { sum+=t&0x0001; t=t>>1; } min++; } printf("%d\n",sum); } } return 0; }
然后是这种位运算的升级版本:
#include "stdio.h" int main() { int T,i; scanf( "%d", &T ); while( T-- ) { int N, beg = 1, end = 1, ans = 0; scanf( "%d", &N ); for(i = 1; i < N; ++i ) { beg <<= 1; end <<= 1;} end <<= 1, end -= 1; for(i = beg; i <= end; ++i ) { int t = i; while( t > 0 ) { if( t & 1 ) ++ans; t >>= 1; } } printf( "%d\n", ans ); } return 0; }
还有另一种算法:按照概率算:
一个n为二进制,一共有2^(n-1)个数字
首位一定是1,其他位要么是1,要么是0,而且0和1出现的次数是相同的,那么我们可以认为其他位出现的都是1/2
那么你要求的和就是 sum=2^(n-1)*(1+(n-1)/2);
化简得 sum=2^(n-2)*(n+1);
上代码,太简洁了
#include <stdio.h> #include <math.h> int main() { double a,b,n; int T; scanf("%d",&T); while(T--) { scanf("%lf",&n); b=pow(2.0,n-2)*(n+1); printf("%.0lf\n",b); } return 0; }
还有一种,我也没看懂: (郁闷)
#include "stdio.h" int main() { int ans[22],base = 1,T,i; ans[1] = 1; for(i = 2; i <= 20; ++i ) { ans[i] = 2 * ans[i-1] + base; base <<= 1; printf("%d %d\n",ans[i],base); } scanf( "%d", &T ); while( T-- ) { int N; scanf( "%d", &N ); printf( "%d\n", ans[N] ); } return 0; }
标签:
原文地址:http://www.cnblogs.com/tianyong/p/4178507.html