• C语言中的位操作(15)--确定log10(N)的整数部分


    本篇文章介绍一个整数的以10为底的对数的整数部分,即对于整数N,求log10(N)整数部分

    方法一 :

    unsigned int v; //32位非0整数 
    int r;          // r保存结果
    int t;          //临时变量
    
    static unsigned int const PowersOf10[] = 
        {1, 10, 100, 1000, 10000, 100000,
         1000000, 10000000, 100000000, 1000000000};
    
    t = (IntegerLogBase2(v) + 1) * 1233 >> 12; //使用之前介绍过的以2为底的对数的求法
    r = t - (v < PowersOf10[t]);

    原理:

    求log10(N)的时候用到了之前介绍过的求log2(N)的方法,通过对数的换底公式:log10(v) = log2(v) / log2(10),我们需要乘以1/log2(10),数值上近似1233/4096,或将1233右移12位,加1的作用是IntegerLogBase2向下取整。最后,既然所得值t仅仅是近似的,并且可以修正,准确值是通过将结果减去v<PowersOf10[t].

    方法二(常规方法):

    unsigned int v; // 32位目标整数 
    int r;          // r保存结果
    r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : 
        (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : 
        (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  • 相关阅读:
    antd Icon
    antd button
    tree 向上查找(更新删除后页面的数据)
    tree 向下查找 (删除整条tree)
    tree结构统一修改属性名(递归)
    json转换为tree对象(递归)
    python测试题
    c函数练习
    飞机一只
    python1119作业1
  • 原文地址:https://www.cnblogs.com/xueda120/p/3155869.html
Copyright © 2020-2023  润新知