模板 计算1的个数

【模板】计算1的个数

 

 1 __int64 CountOne(__int64 n)
 2 {
 3     __int64 count =0;
 4     if (n ==0)
 5         count =0;
 6     else if (n >1&& n <10)
 7     count =1;
 8     else
 9     {
10         __int64 highest = n;
11         __int64 bit =0;
12         while (highest >=10)
13         {
14             highest = highest /10;
15             bit++;
16         }
17 
18         __int64 weight = (__int64)pow(10, bit);
19         if (highest ==1)
20         {
21             count = CountOne(weight -1)+ CountOne(n - weight)+ n - weight +1;
22         }
23         else
24         {
25             count = highest * CountOne(weight -1)+ CountOne(n - highest * weight) + weight;
26         }
27     }
28     return count;
29 }
30 31 publiclong CountOne2(long n)
32 {
33     long count =0;
34     long i =1;
35     long current =0,after =0,before =0;
36     while((n / i) !=0)
37     {
38         current = (n / i) %10;
39         before = n / (i *10);
40         after = n - (n / i) * i;
41         if (current >1)
42             count = count + (before +1) * i;
43         else if (current ==0)
44         count = count + before * i;
45         else if(current ==1)
46         count = count + before * i + after +1;
47 
48         i = i *10;
49     }
50     return count;
51 }
原文地址:https://www.cnblogs.com/jeff-wgc/p/4472925.html