Open In App

Count digits

Last Updated : 28 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number n, the task is to return the count of digits in this number.

Example:

Input: n = 1567
Output: 4
Explanation: There are 4 digits in 1567, which are 1, 5, 6 and 7.

Input: n = 255
Output: 3
Explanation: The are 3 digits in 256, which are 2, 5 and 5.

Input: n = 58964
Output: 5
Explanation: There are 5 digits in 58964, which are 5, 8, 9, 6 and 4.

[Expected Approach] Iterative Solution to count digits in an integer

The idea is to count the digits by removing the digits from the input number starting from right(least significant digit) to left(most significant digit) till the number is reduced to 0. We are removing digits from the right because the rightmost digit can be removed simply by performing integer division by 10. For eg: n = 1567, then 1567 / 10 = 156.7 = 156(Integer Division).

Count-Digits-Flow-Chart-1-2


C++
// Iterative C++ program to count
// number of digits in a number
#include <bits/stdc++.h>
using namespace std;

int countDigit(int n) {
  	// Base case
    if (n == 0)
        return 1;
  
    int count = 0;
  
  	// Iterate till n has digits remaining
    while (n != 0) {
      
      	// Remove rightmost digit
        n = n / 10;
      
      	// Increment digit count by 1
        ++count;
    }
    return count;
}

int main() {
   int  n = 58964;
    cout <<countDigit(n);
    return 0;
}
C
// Iterative C program to count
// number of digits in a number

#include <stdio.h>

int countDigit(int n) {
  
    // Base case
    if (n == 0)
        return 1;

    int count = 0;
  
    // Iterate till n has digits remaining
    while (n != 0) {
      
        // Remove rightmost digit
        n = n / 10;
      
        // Increment digit count by 1
        ++count;
    }
    return count;
}

int main() {
   int n = 58964;
    printf("%d\n", countDigit(n));
    return 0;
}
Java
import java.io.*;

class GfG {

    // function to count digits
    static int countDigit(int n) {
        // Base case
        if (n == 0)
            return 1;

        int count = 0;
      
        // Iterate till n has digits remaining
        while (n != 0) {
          
            // Remove rightmost digit
            n = n / 10;
          
            // Increment digit count by 1
            ++count;
        }
        return count;
    }

    public static void main(String[] args) {
        int n = 58964;
        System.out.println( countDigit(n));
    }
}
Python
# Iterative Python program to count
# number of digits in a number

def countDigit(n):
  
    # Base case
    if n == 0:
        return 1

    count = 0
    
    # Iterate till n has digits remaining
    while n != 0:
      
        # Remove rightmost digit
        n = n // 10
        
        # Increment digit count by 1
        count += 1

    return count

if __name__ == "__main__":
  n = 58964
  print(countDigit(n))
C#
// C# Code to count number of
// digits in an integer
using System;

class GfG {
  
    static int CountDigit(int n) {
        
        // Base case
        if (n == 0)
            return 1;

        int count = 0;
        
        // Iterate till n has digits remaining
        while (n != 0) {
            
            // Remove rightmost digit
            n = n / 10;
            
            // Increment digit count by 1
            ++count;
        }
        return count;
    }

    static void Main() {
        int n = 58964;
        Console.WriteLine(CountDigit(n));
    }
}
JavaScript
// Iterative JavaScript program to count
// number of digits in a number

function countDigit(n) {
    
    // Base case
    if (n === 0)
        return 1;

    let count = 0;
    
    // Iterate till n has digits remaining
    while (n !== 0) {
        
        // Remove rightmost digit
        n = Math.floor(n / 10);
        
        // Increment digit count by 1
        ++count;
    }
    return count;
}

// Driver code
let n = 58964;
console.log( countDigit(n));

Output
5

Time Complexity : O(log10(n)) or O(number of digits), where n is the input number
Auxiliary Space: O(1) or constant

[Alternate Approach] Removing digits using Recursion

The idea is to remove digits from right by calling a recursive function for each digit. The base condition of this recursive approach is when we divide the number by 10 and the number gets reduced to 0, so return 1 for this operation. Otherwise, Keep dividing the number by 10 this reduces the input number size by 1 and keeps track of the number of sizes reduced.

C++
// Recursive C++ program to count number of
// digits in a number
#include <bits/stdc++.h>
using namespace std;

int countDigit(int n) {
    if (n/10 == 0)
        return 1;
    return 1 + countDigit(n / 10);
}

int main() {
   int n = 58964;
    cout << countDigit(n);
    return 0;
}
C
// Recursive C program to count number of
// digits in a number
#include <stdio.h>

int countDigit(int n) {
    if (n/10 == 0)
        return 1;
    return 1 + countDigit(n / 10);
}

int main() {
   int n = 58964;
    printf("%d", countDigit(n));
    return 0;
}
Java
// JAVA Code to count number of
// digits in an integer
import java.util.*;

class GfG {

    static int countDigit(int n){
        if (n / 10 == 0)
            return 1;
        return 1 + countDigit(n / 10);
    }

    public static void main(String[] args) {
        int n = 58964;
        System.out.print(countDigit(n));
    }
}
Python
# Recursive Python program to count
# number of digits in a number

def countDigit(n):
    if n//10 == 0:
        return 1
    return 1 + countDigit(n // 10)

if __name__ == "__main__":
  n = 58964
  print(countDigit(n))
C#
// C# Code to count number of
// digits in an integer
using System;

class GfG {

    static int countDigit(int n){
        if (n / 10 == 0)
            return 1;
        return 1 + countDigit(n / 10);
    }

    public static void Main() {
        int n = 58964;
        Console.WriteLine( countDigit(n));
    }
}
JavaScript
function countDigit(n) {
    if (parseInt(n / 10) === 0)
        return 1;
    return 1 + countDigit(parseInt(n / 10));
}

// Driver code
var n = 58964;
console.log(countDigit(n));

Output
5

Time Complexity : O(log10(n)) or O(Number of Digits), where n is the input number.
Auxiliary Space : O(log10(n))

[Alternate Approach] Counting digits using log base 10 function

We can use log10(logarithm of base 10) to count the number of digits of positive numbers (logarithm is not defined for negative numbers).
Digit count of n = floor(log10(n) + 1) 

C++
// Log based C++ program to count number of
// digits in a number

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

int countDigit(int n) { return floor(log10(n) + 1); }

int main() {
	int n = 58964;
    cout <<countDigit(n);
    return 0;
}
C
// Log based C program to count number of
// digits in a number
#include <math.h>
#include <stdio.h>

int countDigit(int n) { return floor(log10(n) + 1); }

int main() {
    int n = 58964;
    printf("%d\n", countDigit(n));
    return 0;
}
Java
// Log based Java program to count number of
// digits in a number
import java.util.*;

class GfG {

    static int countDigit(int n) {
        return (int)Math.floor(Math.log10(n) + 1);
    }

    public static void main(String[] args) {
        int n = 58964;
        System.out.print(countDigit(n));
    }
}
Python
# Log based Python program to count number of
# digits in a number
import math

def countDigit(n):
    return math.floor(math.log10(n)+1)

if __name__ == "__main__":
  n = 58964
  print(countDigit(n))
C#
// Log based C# program to count number of
// digits in a number
using System;

class GfG {

    static int countDigit(int n) {
        return (int)Math.Floor(Math.Log10(n) + 1);
    }

    public static void Main() {
        int n = 58964;
        Console.WriteLine(countDigit(n));
    }
}
JavaScript
// Log based Javascript program to count number of
// digits in a number

function countDigit(n) { 
    return Math.floor(Math.log10(n) + 1); 
}

// Driver code
var n = 58964;
console.log( countDigit(n));

Output
5

Time Complexity: O(1) or constant
Auxiliary Space: O(1) or constant

[Alternate Approach] Converting Number to String

We can convert the number into a string and then find the length of the string to get the number of digits in the original number.

C++
// C++ Code to find number of digits by converting number to
// string

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

int countDigit(int n)
{
    // converting number to string using
    // to_string in C++
    string num = to_string(n);

    // calculate the size of string
    return num.length();
}
int main()
{
    int n = 58964;
    cout  << countDigit(n);
    return 0;
}
Java
// Java Code to find number of digits by converting number to
// string

class Main {
    // Function to count digits by converting number to string
    static int countDigit(int n) {
        // Convert number to string
      
        String num = Long.toString(n);
        // Calculate the length of the string
        return num.length();
    }


    public static void main(String[] args) {
        int n = 58964;
        System.out.println( countDigit(n));
    }
}
Python
# Python Code to find number of digits by converting number to
# string

def count_digit(n):
  
    # Convert number to string
    num = str(n)
    
    # Calculate the length of the string
    return len(num)

if __name__ == "__main__":
  n = 58964
  print( count_digit(n))
C#
// C# Code to find number of digits by converting number to
// string
using System;

 class GfG {
     static int CountDigit(int n) {
       
        // Convert number to string
        string num = n.ToString();
        // Calculate the length of the string
        return num.Length;
    }

    public static void Main() {
        int n = 58964;
        Console.WriteLine( CountDigit(n));
    }
}
JavaScript
// JavaScript Code to find number of digits by converting number to
// string
function countDigit(n) {

    // Convert number to string
    let num = n.toString();
    
    // Calculate the length of the string
    return num.length;
}

// Driver code
let n = 58964;
console.log( countDigit(n));

Output
5

Time Complexity: O(1) or constant
Auxiliary Space:  O(Number of digits)



Next Article

Similar Reads