【模板】计算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 }

 

相关文章:

  • 2021-11-27
  • 2022-12-23
  • 2022-01-22
  • 2022-12-23
  • 2021-12-30
  • 2021-10-26
  • 2021-11-13
猜你喜欢
  • 2021-09-05
  • 2021-05-03
  • 2021-11-28
  • 2022-02-15
  • 2021-10-19
  • 2021-06-05
  • 2022-01-25
相关资源
相似解决方案