Skip to content

Count the Number of Digits in an Integer

This is an example problem for counting digits in an integer. Solving this problem helps you find the place values and how they are represented in the decimal number system. Let’s see some approaches we can take to solve this algorithmic problem. Approach

Gopi Gorantala
Gopi Gorantala
5 min read

Table of Contents

In this article, we will write code to count the number of digits in an integer.

How to count the number of digits in an integer

Given a decimal number, continue dividing it by ten until it reaches 0 and records the remainder at each step.

The resulting list of remainders is the equivalent place value of the Integer.

Example:

Input: 125

Output: 3

The illustration below explains the process of counting the digits in an integer.

Number Number = (number / 10) Count
125 12 1
12 1 2
1 0 3

Problem statement

Given an integer, return the number of digits in an integer input.

Example #1:

Input:  n = 125

Output: 3

Explanation: The number of digits present in input `n` is 3 (1, 2, 5).

Example #2:

Input:  n = 1256

Output: 4

Explanation: The number of digits present in input `n` is 4 (1, 2, 5, 6).

Intuition

This is an example problem for counting digits in an integer. Solving this problem helps you find the place values and how they are represented in the decimal number system.

There are 4 different ways to solve this problem.

  1. Division approach
  2. Logarithmic
  3. Recursive
  4. String conversion

Division approach [while loop]

In this program, while loop is iterated until the expression number != 0 is evaluated to 0 (false).

Let’s see the iterations for number = 125.

Iterations

  • After the first iteration, n(125) will be divided by 10, and its value will be 12, and the count is incremented to 1.
  • After the second iteration, the value of n(12) will be 1 and the count is incremented to 2.
  • After the third iteration, the value of n(1) will be 0, and the count is incremented to 3.

Then the expression is evaluated as false, as n is 0, and the loop terminates.

Solutions

Java:

class CountDigits {
    private static int countDigits(int n){
        int count = 0;
        
        while (n > 0) {
            ++count;
            n /= 10;
        }
        
        return count;
    }

    public static void main(String[] args) {
        int number = 125;
        System.out.println("Number of digits : " + countDigits(number));
    }
}

// Output: Number of digits : 3

Python:

def countDigit(n):
  count=0
  while n>0:
    count+=1
    n=n//10
  return count

n=125
print("Number of digits: ",countDigit(n))

JavaScript:

const CountDigits = n => {
    let count = 0;

    while (n > 0) {
        n = Math.floor(n / 10);
        ++count;
    }
    
    return count;
};

console.log('Number of Digits:', CountDigits(125));

// Output: Number of digits : 3

C++:

#include <iostream>
using namespace std;

int countDigits(int n){
  int count = 0;
  while (n != 0){
    count++;
    n /= 10;
  }
    return count;
}

int main() {
  int n = 125;
  cout << "Number of digits : " << countDigits(n) << endl;
}

// Output: Number of digits : 3

Typescript:

export const CountDigits = (n: number): number => {
    let count: number = 0;

    while (n > 0) {
        n = Math.floor(n / 10);
        ++count;
    }

    return count;
};

console.log('Number of Digits:', CountDigits(125));

// Output: Number of digits : 3

Complexity analysis

Time complexity: O(n)

The run time depends on the number of digits in n. In the worst case, it iterates through all the digits until it becomes 0.

Space complexity: O(1)

The space complexity is O(1) since no additional space is allocated.

Logarithmic approach

We can use log10 (logarithm of base 10) to count the number of digits of positive numbers.

Digit count of N = upper bound of log10(N).

Note: Logarithms are not defined for negative numbers.

log(0) is infinity

Solutions

Java:

class CountDigits {
    private static int countDigits(int n){
        return n != 0 ? ((int) Math.floor(Math.log10(n) + 1)) : -1;
    }

    public static void main(String[] args) {
        int number = 125;
        System.out.println("Number of digits : " + countDigits(number));
    }
}

// Output: Number of digits : 3

Python:

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

n = 125
print("number of digits : " , countDigit(n))

JavaScript:

const CountDigits = (n) => {
    return n !== 0 ? Math.floor(Math.log10(n) + 1) : -1;
};

console.log('Number of Digits:', CountDigits(125));

// Output: Number of digits : 3

C++:

#include <iostream>
#include <cmath>

using namespace std;

int countDigits(int number){
  return int(log10(number) + 1);
}

int main() {
  int number = 125;
  cout << "Number of digits  : " << countDigits(number) << endl;
}

// Output: Number of digits : 3

TypeScript:

export const CountDigits = (n: number): number => {
    return n !== 0 ? Math.floor(Math.log10(n) + 1) : -1;
};

console.log('Number of Digits:', CountDigits(125));

// Output: Number of digits : 3

Some of the other ways to achieve this are shown below.

These approaches are not recommended, as the time and space complexities are high.

Recursive approach

This recursive approach might be ineffective when dealing with a large integer. n.

A recursive call adds a stack entry every time it runs and again when once it reaches the base condition. It then backtracks and executes each recursive function.

Solutions

Java:

class CountDigits {
    private static int helper(int n) {
        // base checks
        if (n == 0) {
            return 0;
        }
        
        return (1 + helper(n / 10));
    }

    public static void main(String[] args) {
        int number1 = 125;
        int number2 = 00125;
        
        //if input has any leading zeros, below line handles it.
        int parsedNum2 = Integer.parseInt(Integer.toString(number2,8));

        System.out.println("Number of digits : " + helper(number1));
        System.out.println("Number of digits : " + helper(parsedNum2));
    }
}

// Outputs:
// Number of digits : 3
// Number of digits : 3

Python:

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

n = 125
print("Number of digits : " , countDigit(n))

JavaScript:

const CountDigits = (number) => {

    function helper(n) {
        //base checks
        if (n === 0) {
            return 0;
        }
        
        return (1 + helper(Math.floor(n / 10)));
    }

    return helper(number);
};

console.log('Number of Digits:', CountDigits(125));

// Output: Number of digits : 3

C++:

#include <iostream>
using namespace std;

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

int main() {
  int number = 125;
  cout << "Number of Digits: " << countDigits(number);
  return 0;
}

// Output: Number of digits : 3

TypeScript:

export const CountDigits = (n: number): number => {
    function helper(value: number): number {
        //base checks
        if (value === 0) {
            return 0;
        }
        return (1 + helper(Math.floor(value / 10)));
    }
    return helper(n);
};

console.log('Number of Digits:', CountDigits(125));

// Output: Number of digits : 3

Convert to string

This is one of the ways to implement/solve the problem, but it is not recommended, as we are converting one type of data to another.

Solutions

Java

class CountDigits {
    private static int helper(int n) {
        // you can also use String.valueOf(number) to convert int to string.
        String num = Integer.toString(n);

        return num.length();
    }

    public static void main(String[] args) {
        int number = 125;
        System.out.println("Number of digits : " + helper(number));
    }
}

// Output: Number of digits : 3

Python

def count_digits(n):
    n=str(n)
    return len(n)

n = 125
print("Number of digits : " , count_digits(n))

JavaScript

const CountDigits = n => {
    return n.toString().length;
};

console.log('Number of Digits:', CountDigits(125));

// Output: Number of digits : 3

C++

#include <iostream>
#include <string>
using namespace std;

int main() {
  int n = 125;
  string str = to_string(n);
  cout << "Number of digits : " << str.length() << endl;
  return 0;
}

// Output: Number of digits : 3

TypeScript

export const CountDigits = (n: number): number => {
    return n.toString().length;
};

console.log('Number of Digits:', CountDigits(125));

// Output: Number of digits : 3

Note

The string approach is just for your learning and understanding of Bitwise concepts. If you pass number = 0, the above code returns 1 instead of 0, which is incorrect.

Coding Interview QuestionsData Structures and AlgorithmsBit Manipulation

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Leetcode 217: Contains Duplicate

This question marks the first problem when working on duplicate data, either integers or strings etc. Companies that have asked this in their coding interview are Amazon, Apple, Netflix, Google, Microsoft, Adobe, Facebook, and many more top tech companies. Problem statement Given an integer array nums, return true if any

Leetcode 217: Contains Duplicate
Members Public

Leetcode 121: Best Time To Buy and Sell Stock

The Best time to buy and sell stock problem is a classic problem that can be solved using the Greedy approach. This is one of the most popular questions asked in such interviews. Companies that have asked this in their coding interview are Facebook, Amazon, Apple, Netflix, Google, Microsoft, Adobe,

Leetcode 121: Best Time To Buy and Sell Stock
Members Public

Bit Manipulation Course Overview

Overview In this course, you will learn how to solve problems using bit manipulation, a powerful technique that can be used to optimize your algorithmic and problem-solving skills. This is one of the most important/critical topics when someone starts preparing for coding interviews for FAANG companies. To kick things