Problem:
Find the sum of all bits from numbers 1 to N.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
#include <stdio.h> int main() { //code int t,n,i,ans; int powerOfTwo,dividend,m; int arr[30]; arr[0]=1; arr[1]=2; arr[2]=5; arr[3]=13; int gapOfNumber=8; for(i=4;i<30;i++) { arr[i]=(arr[i-1])*2+(gapOfNumber-1); gapOfNumber=gapOfNumber*2; } scanf("%d",&t); while(t--) { scanf("%d",&n); ans=0; while(n) { m=n; dividend=1; powerOfTwo=0; while(m) { if(m/2) { powerOfTwo+=1; dividend*=2; m=m/2; } else break; } n=n%dividend; //printf("%d = div\npowerOfTwo=%d\n",n,powerOfTwo); ans+=(arr[powerOfTwo]+n); } printf("%d\n",ans); } return 0; } |