Count digits of number without loop C++

counter = log(num) / log(10)

in c++:

#include <cmath>
....
counter = num == 0 ? 1 : log10(std::abs(num)) + 1;

what you want is the log function.

cplusplus - log10

cplusplus - std::abs


Easy way although somewhat expensive, turn your number to string and take its size like the example below:

#include <iostream>
#include <string>

int main() {
  int i = 1232323223;
  std::string str = std::to_string(std::abs(i));
  std::cout << "Number of Digits: " << str.size() <<std::endl;
}

LIVE DEMO


One way is to use sprintf, since it returns the number of characters emitted:

int digits(int n)
{
    char s[32];
    int len = sprintf(s, "%d", n);
    if (n < 0) len--; // NB: handle negative case
    return len;
}

Tags:

C++