Get number of digits of a number

前端 未结 9 1053
挽巷
挽巷 2021-01-07 11:39

I have a number like this: int num = 36729; and I want to get the number of digits that compose the number (in this case 5 digits).

How can I do this?

相关标签:
9条回答
  • 2021-01-07 12:13

    Can't you do this ?

        int num = 36729;
        num.ToString().Length
    
    0 讨论(0)
  • 2021-01-07 12:16

    Use this formula:

    if(num)
      return floor(log10(abs((double) num)) + 1);
    
    return 1;
    
    0 讨论(0)
  • 2021-01-07 12:18

    Hint: use the / and the % operators.

    0 讨论(0)
  • 2021-01-07 12:18

    Inefficient, but strangely elegant...

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        // code to get value
        char str[50];
        sprintf(str, "%d", value);
    
        printf("The %d has %d digits.\n", value, strlen(str));
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-07 12:20
    int findcount(int num) 
    { 
        int count = 0; 
        if(num != 0){
          while(num) { 
              num /= 10; 
              count ++; 
          } 
          return count ; 
        }
        else
          return 1;
    } 
    
    0 讨论(0)
  • 2021-01-07 12:26

    For any input other than 0, compute the base-10 logarithm of the absolute value of the input, take the floor of that result and add 1:

    int dig;
    ...
    if (input == 0)
      dig = 1;
    else
      dig = (int) floor(log10(abs((double) input))) + 1;
    

    0 is a special case and has to be handled separately.

    0 讨论(0)
提交回复
热议问题