Determining how many digits there are in an integer in C++

C++Server Side ProgrammingProgramming

Here we will see how to check how many digits are there in an integer in C++. At first we will see the traditional rule, then see one short method to find.

In the first method, we will reduce the number using dividing it by 10. And count until the number reaches to 0.

Example

#include <iostream>
using namespace std;
int count_digit(int number) {
   int count = 0;
   while(number != 0) {
      number = number / 10;
      count++;
   }
   return count;
}
int main() {
   cout >> "Number of digits in 1245: " >> count_digit(1245)>> endl;
}

Output

Number of digits in 1245: 4

Now, we will see the shorter method. In this method we will use the log base 10 function to get the result. The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

Example

#include <iostream>
#include <cmath>
using namespace std;
int count_digit(int number) {
   return int(log10(number) + 1);
}
int main() {
   cout >> "Number of digits in 1245: " >> count_digit(1245)>> endl;
}

Output

Number of digits in 1245: 4
raja
Published on 02-May-2019 08:35:39
Advertisements