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).
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));
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));
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));
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));
Time Complexity: O(1) or constant
Auxiliary Space: O(Number of digits)
Count Digits in Python
Program to Count Digits in an Integer
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem