计算给定正数的总位数,而不在C中循环

时间:2010-06-01 09:59:10

标签: c

如何计算给定正数的总位数而不在C中循环?

4 个答案:

答案 0 :(得分:6)

对于整数,取数字的log10,向下舍入,然后加一。

<强> TEST:

#include <math.h>
#include <stdio.h>

int 
num_digits(unsigned long number)
{
    return (int)(floor(log10((double)number)) + 1.0);
}

int
main(int argc, char **argv)
{
    unsigned long test_numbers[] = {
        1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 99999, 100000, 999999,
        123456789ul,
        999999999ul,
        0
    };

    unsigned long *ptr;
    for(ptr = test_numbers; *ptr; ptr++)
    {
        printf("Number of digits in %lu: %d\n", *ptr, num_digits(*ptr));
    }

    return 0;
}

输出:

Number of digits in 1: 1
Number of digits in 9: 1
Number of digits in 10: 2
Number of digits in 99: 2
Number of digits in 100: 3
Number of digits in 999: 3
Number of digits in 1000: 4
Number of digits in 9999: 4
Number of digits in 10000: 5
Number of digits in 99999: 5
Number of digits in 100000: 6
Number of digits in 999999: 6
Number of digits in 123456789: 9
Number of digits in 999999999: 9

答案 1 :(得分:1)

一种可能的解决方案,假设16位整数值和逻辑表达式评估为0或1.如果您担心可移植性,可以用(u > 99) ? 1 : 0替换条件。

int digits( unsigned u)
{
    return 1 + (u > 9) + (u > 99) + (u > 999) + (u > 9999);
}

答案 2 :(得分:0)

两种解决方案!

int digit_count(unsigned int n)
{
   if (n < 10)
      return 1;
   else
      return (1 + digit_count(n / 10));
}

   unsigned int n = 50;
   int i = 0;

HACK:
   i++;

   if (n < 10)
   {
      printf("Digits: %d\n", i);
   }
   else
   {
      n /= 10;

      goto HACK;
   }

不要恨我最后一个:(

答案 3 :(得分:0)

return snprintf(0, 0, "%d", num);