zoukankan      html  css  js  c++  java
  • 模板 计算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 }
  • 相关阅读:
    单例模式创建
    盛最多水的容器
    魔术索引
    钢条切割
    比较版本号
    矩阵中的路径
    机器人的运动范围
    计网基础问题
    Linux 下android环境的配置
    Fedora15下安装Android开发环境
  • 原文地址:https://www.cnblogs.com/jeff-wgc/p/4472925.html
Copyright © 2011-2022 走看看