Get number of digits of a number

前端 未结 9 1054
挽巷
挽巷 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:36
    1. The number of digits of an integer n in any base is trivially obtained by dividing until you're done:
    unsigned int number_of_digits = 0;
    do {
        ++number_of_digits; 
        n /= base;
    } while (n);
    
    1. Not necessarily the most efficient, but one of the shortest and most readable using C++: std::to_string(num).length()

    2. And there is a much better way to do it:

    #include<cmath>
    ...
    int size = trunc(log10(num)) + 1
    ...
    
    0 讨论(0)
  • 2021-01-07 12:37
    int digits = 0;
    while (num > 0) {
      ++digits;
      num = num / 10;
    }
    
    0 讨论(0)
  • 2021-01-07 12:38
    int unsigned_digit_count(unsigned val) {
        int count = 0;
        do {
            count++;
            val /= 10;
        } while (val);
        return count;
    }
    
    int digit_count(int val) {
        if (val < 0) {
            return 1+unsigned_digit_count(-val); // extra digit for the '-'
        } else {
            return unsigned_digit_count(val);
        }
    }
    
    0 讨论(0)
提交回复
热议问题