计算1的个数

Posted mqxnongmin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算1的个数相关的知识,希望对你有一定的参考价值。

__int64 CountOne(__int64 n)
{
    __int64 count =0;
    if (n ==0)
        count =0;
    else if (n >1&& n <10)
    count =1;
    else
    {
        __int64 highest = n;
        __int64 bit =0;
        while (highest >=10)
        {
            highest = highest /10;
            bit++;
        }

        __int64 weight = (__int64)pow(10, bit);
        if (highest ==1)
        {
            count = CountOne(weight -1)+ CountOne(n - weight)+ n - weight +1;
        }
        else
        {
            count = highest * CountOne(weight -1)+ CountOne(n - highest * weight) + weight;
        }
    }
    return count;
}
<pre name="code" class="cpp">publiclong CountOne2(long n)
{
    long count =0;
    long i =1;
    long current =0,after =0,before =0;
    while((n / i) !=0)
    {
        current = (n / i) %10;
        before = n / (i *10);
        after = n - (n / i) * i;
        if (current >1)
            count = count + (before +1) * i;
        elseif (current ==0)
        count = count + before * i;
        elseif(current ==1)
        count = count + before * i + after +1;

        i = i *10;
    }
    return count;

}




以上是关于计算1的个数的主要内容,如果未能解决你的问题,请参考以下文章

如何在 python 中并行化以下代码片段?

10个JavaScript代码片段,使你更加容易前端开发。

10个JavaScript代码片段,使你更加容易前端开发。

从JVM的角度看JAVA代码--代码优化

Vue3官网-高级指南(十七)响应式计算`computed`和侦听`watchEffect`(onTrackonTriggeronInvalidate副作用的刷新时机`watch` pre)(代码片段

golang代码片段(摘抄)