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

In this tutorial, we will be learning about determining how many digits there are in an integer in C++.

How many digits there are in an integer in C++

Here, we will discuss different approaches by which we can get the number of digits in an integer.

Approach 1

Iterative Approach

The sample code…

#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n,count=0;
    cin>>n;
    while(n>0)
    {
        count++;
        n=n/10;
    }
    cout<<"The total number of digits are "<<count;
    return 0;
}

Output :

123
The total number of digits are 3

Explanation :

1. First the integer is being taken from the user

2. Then, the while loop is executed until n holds a positive value.

3. Then, the value of the count gets incremented and n becomes n/10 at each iteration.

Approach 2

Recursive Approach

The sample code…

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int count(int n)
{
    if(n/10==0)
    return 1;
    else
    return 1+count(n/10);
}
int main()
{
    int n;
    cin>>n;
    int res=count(n);
    cout<<"The total number of digits are "<<res;
    return 0;
}

Output :

123
The total number of digits are 3

Explanation :

1. Firstly the integer is being taken from the user in the main function. then, the count function is called with parameter as n.

2. In the count function if n/10 gives 0 then we are returning 1. else, the count function is recursively called by adding 1 to it.

3. Then, the count function returns the count of the digits. then that is printed in the main function.

Approach 3

Log-Based Approach

The sample code…

#include <iostream> 
#include<bits/stdc++.h> 
using namespace std; 
int count(int n) 
{ 
    return (log10(n)+1); 
} 
int main() 
{ 
    int n; 
    cin>>n; 
    int res=count(n); 
    cout<<"The total number of digits are "<<res; 
    return 0; 
}

Output :

123
The total number of digits are 3

Explanation :

1. First, the integer is taken from the user in the main function.

2. Then the count function is called with the parameter as n.

3. Then the count of the digits is printed by using log10.

Leave a Reply

Your email address will not be published.