算上位数 - 哪种方法最有效? [英] count number of digits - which method is most efficient?

查看:298
本文介绍了算上位数 - 哪种方法最有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有查找在给定数目的用户号码的位数超过一个溶液

There are more than one solution for finding the-number-of-digits in a given number.

例如:

方法1:

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

方法2:

int findn(int num)
{
    int n = 0;
    while(num) {
        num /= 10;
        n++;
    }
    return n;
}

方法3:

int findn(int num)
{
    /* math.h included */
    return (int) log10(num) + 1;
}

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

The question is - what is the most efficient method? I know method-2 is O(n) but what about method-1 and method-3? How do I find the run-time complexity of library functions?

推荐答案

下面是更有效的:

int findn(int num)
{
   if ( num < 10 )
      return 1;
   if ( num < 100 )
      return 2;
   //continue until max int
}

您可以做一个二进制搜索进一步优化这一点,但是这将是矫枉过正。

You could optimize this even further by doing a binary search, but that would be overkill.

这篇关于算上位数 - 哪种方法最有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆