Shredded Code: statistics of the total number of 1 to n binary number 1 appears

Subject description:

Shredded code for mutual entertainment title.

Appearing in a number of statistics that represent the binary number of n 1 to n.

 

Analysis of ideas:

A thought: the direct approach is to iterate from 1 to n, and 1 for each number do with the operation, then, for this number continues to do the right operation, and continue to do the operation and 1, until the current number to zero. Such algorithm complexity is O (nlogn).

Ideas II: optimization of time complexity, consider using space for time. Using n & (n-1) This operation can be removed at the end of 1. Recursive f (n) = 1 + f (n & (n-1)). Such is the use of space for time, time complexity is O (n).

 

Code:

A thought:

 1 int numZeros(int n)
 2 {
 3     int res=0;
 4     for(int i=1; i<=n; i++)
 5     {
 6         while(i>0)
 7         {
 8             if(i&1==1)
 9                 res++;
10             i = i>>1;
11          }   
12     }
13     return res;
14 }

 

Thinking two:

 1 int numZeros(int n)
 2 {
 3     vector<int>f(n+1, 0);
 4     int res=0;
 5     for(int i=1; i<=n; i++)
 6     {
 7         f[i] = 1+f[i&(i-1)];
 8         res += f[i];
 9     }
10     return res;
11 }

 

Guess you like

Origin www.cnblogs.com/LJ-LJ/p/11609233.html