相关疑难解决方法(0)

计算位数 - 哪种方法最有效?

有一种以上的解决方案可以找到给定数字中的数字位数.

例如:

方法1:

int findn(int num)
{
    char snum[100];
    sprintf(snum, "%d", num);
    return strlen(snum);
}
Run Code Online (Sandbox Code Playgroud)

方法2:

int findn(int num)
{
    if (num == 0) return 1;
    int n = 0;
    while(num) {
        num /= 10;
        n++;
    }
    return n;
}
Run Code Online (Sandbox Code Playgroud)

方法-3:

int findn(int num)
{
    /* math.h included */
    return (int) log10(num) + 1;
}
Run Code Online (Sandbox Code Playgroud)

问题是 - 什么是最有效的方法?我知道方法-2 O(n)但是方法1和方法3怎么样?如何找到库函数的运行时复杂性?

c time-complexity

21
推荐指数
4
解决办法
4万
查看次数

标签 统计

c ×1

time-complexity ×1