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; }
還有一種,我也沒看懂: (鬱悶)spa
#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; }