Count numbers having 0 as a digit
Last Updated :
23 Jul, 2025
Problem: Count how many integers from 1 to N contains 0 as a digit.
Examples:
Input: n = 9
Output: 0
Input: n = 107
Output: 17
The numbers having 0 are 10, 20,..90, 100, 101..107
Input: n = 155
Output: 24
The numbers having 0 are 10, 20,..90, 100, 101..110,
120, ..150.
A naive solution is discussed in previous post
In this post an optimized solution is discussed. Let's analyze the problem closely.
Let the given number has d digits .
The required answer can be computed by computing the following two values:
- Count of 0 digit integers having maximum of d-1 digits.
- Count of 0 digit integers having exactly d digits (less than/ equal to the given number of course!)
Therefore, the solution would be the sum of above two.
The first part has already been discussed here.
How to find the second part?
We can find the total number of integers having d digits (less than equal to given number), which don't contain any zero.
To find this we traverse the number, one digit at a time.
We find count of non-negative integers as follows:
- If the number at that place is zero, decrement counter by 1 and break (because we can't move any further, decrement to assure that the number itself contains a zero)
- else , multiply the (number-1), with power(9, number of digits to the right to it)
Let's illustrate with an example.
Let the number be n = 123. non_zero = 0
We encounter 1 first,
add (1-1)*92 to non_zero (= 0+0)
We encounter 2,
add (2-1)*91 to non_zero (= 0+9 = 9)
We encounter 3,
add (3-1)*90 to non_zero (=9+3 = 12)
We can observe that non_zero denotes the number of integer consisting of 3 digits (not greater than 123) and don't contain any zero. i.e., (111, 112, ....., 119, 121, 122, 123) (It is recommended to verify it once)
Now, one may ask what's the point of calculating the count of numbers which don't have any zeroes?
Correct! we're interested to find the count of integers which have zero.
However, we can now easily find that by subtracting non_zero from n after ignoring the most significant place.i.e., In our previous example zero = 23 - non_zero = 23-12 =11 and finally we add the two parts to arrive at the required result!!
Below is implementation of above idea.
C++
//Modified C++ program to count number from 1 to n with
// 0 as a digit.
#include <bits/stdc++.h>
using namespace std;
// Returns count of integers having zero upto given digits
int zeroUpto(int digits)
{
// Refer below article for details
// https://www.geeksforgeeks.org/dsa/count-positive-integers-0-digit/
int first = (pow(10,digits)-1)/9;
int second = (pow(9,digits)-1)/8;
return 9 * (first - second);
}
// utility function to convert character representation
// to integer
int toInt(char c)
{
return int(c)-48;
}
// counts numbers having zero as digits upto a given
// number 'num'
int countZero(string num)
{
// k denoted the number of digits in the number
int k = num.length();
// Calculating the total number having zeros,
// which upto k-1 digits
int total = zeroUpto(k-1);
// Now let us calculate the numbers which don't have
// any zeros. In that k digits upto the given number
int non_zero = 0;
for (int i=0; i<num.length(); i++)
{
// If the number itself contains a zero then
// decrement the counter
if (num[i] == '0')
{
non_zero--;
break;
}
// Adding the number of non zero numbers that
// can be formed
non_zero += (toInt(num[i])-1) * (pow(9,k-1-i));
}
int no = 0, remaining = 0,calculatedUpto=0;
// Calculate the number and the remaining after
// ignoring the most significant digit
for (int i=0; i<num.length(); i++)
{
no = no*10 + (toInt(num[i]));
if (i != 0)
calculatedUpto = calculatedUpto*10 + 9;
}
remaining = no-calculatedUpto;
// Final answer is calculated
// It is calculated by subtracting 9....9 (d-1) times
// from no.
int ans = zeroUpto(k-1) + (remaining-non_zero-1);
return ans;
}
// Driver program to test the above functions
int main()
{
string num = "107";
cout << "Count of numbers from 1" << " to "
<< num << " is " << countZero(num) << endl;
num = "1264";
cout << "Count of numbers from 1" << " to "
<< num << " is " <<countZero(num) << endl;
return 0;
}
Java
//Modified Java program to count number from 1 to n with
// 0 as a digit.
public class GFG {
// Returns count of integers having zero upto given digits
static int zeroUpto(int digits)
{
// Refer below article for details
// https://www.geeksforgeeks.org/dsa/count-positive-integers-0-digit/
int first = (int) ((Math.pow(10,digits)-1)/9);
int second = (int) ((Math.pow(9,digits)-1)/8);
return 9 * (first - second);
}
// utility function to convert character representation
// to integer
static int toInt(char c)
{
return (int)(c)-48;
}
// counts numbers having zero as digits upto a given
// number 'num'
static int countZero(String num)
{
// k denoted the number of digits in the number
int k = num.length();
// Calculating the total number having zeros,
// which upto k-1 digits
int total = zeroUpto(k-1);
// Now let us calculate the numbers which don't have
// any zeros. In that k digits upto the given number
int non_zero = 0;
for (int i=0; i<num.length(); i++)
{
// If the number itself contains a zero then
// decrement the counter
if (num.charAt(i) == '0')
{
non_zero--;
break;
}
// Adding the number of non zero numbers that
// can be formed
non_zero += (toInt(num.charAt(i))-1) * (Math.pow(9,k-1-i));
}
int no = 0, remaining = 0,calculatedUpto=0;
// Calculate the number and the remaining after
// ignoring the most significant digit
for (int i=0; i<num.length(); i++)
{
no = no*10 + (toInt(num.charAt(i)));
if (i != 0)
calculatedUpto = calculatedUpto*10 + 9;
}
remaining = no-calculatedUpto;
// Final answer is calculated
// It is calculated by subtracting 9....9 (d-1) times
// from no.
int ans = zeroUpto(k-1) + (remaining-non_zero-1);
return ans;
}
// Driver program to test the above functions
static public void main(String[] args) {
String num = "107";
System.out.println("Count of numbers from 1" + " to "
+ num + " is " + countZero(num));
num = "1264";
System.out.println("Count of numbers from 1" + " to "
+ num + " is " +countZero(num));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to count number from 1 to n
# with 0 as a digit.
# Returns count of integers having zero
# upto given digits
def zeroUpto(digits):
first = int((pow(10, digits) - 1) / 9);
second = int((pow(9, digits) - 1) / 8);
return 9 * (first - second);
# counts numbers having zero as digits
# upto a given number 'num'
def countZero(num):
# k denoted the number of digits
# in the number
k = len(num);
# Calculating the total number having
# zeros, which upto k-1 digits
total = zeroUpto(k - 1);
# Now let us calculate the numbers which
# don't have any zeros. In that k digits
# upto the given number
non_zero = 0;
for i in range(len(num)):
# If the number itself contains a zero
# then decrement the counter
if (num[i] == '0'):
non_zero -= 1;
break;
# Adding the number of non zero numbers
# that can be formed
non_zero += (((ord(num[i]) - ord('0')) - 1) *
(pow(9, k - 1 - i)));
no = 0;
remaining = 0;
calculatedUpto = 0;
# Calculate the number and the remaining
# after ignoring the most significant digit
for i in range(len(num)):
no = no * 10 + (ord(num[i]) - ord('0'));
if (i != 0):
calculatedUpto = calculatedUpto * 10 + 9;
remaining = no - calculatedUpto;
# Final answer is calculated. It is calculated
# by subtracting 9....9 (d-1) times from no.
ans = zeroUpto(k - 1) + (remaining - non_zero - 1);
return ans;
# Driver Code
num = "107";
print("Count of numbers from 1 to",
num, "is", countZero(num));
num = "1264";
print("Count of numbers from 1 to",
num, "is", countZero(num));
# This code is contributed by mits
C#
// Modified C# program to count number from 1 to n with
// 0 as a digit.
using System;
public class GFG{
// Returns count of integers having zero upto given digits
static int zeroUpto(int digits)
{
// Refer below article for details
// https://www.geeksforgeeks.org/dsa/count-positive-integers-0-digit/
int first = (int) ((Math.Pow(10,digits)-1)/9);
int second = (int) ((Math.Pow(9,digits)-1)/8);
return 9 * (first - second);
}
// utility function to convert character representation
// to integer
static int toInt(char c)
{
return (int)(c)-48;
}
// counts numbers having zero as digits upto a given
// number 'num'
static int countZero(String num)
{
// k denoted the number of digits in the number
int k = num.Length;
// Calculating the total number having zeros,
// which upto k-1 digits
int total = zeroUpto(k-1);
// Now let us calculate the numbers which don't have
// any zeros. In that k digits upto the given number
int non_zero = 0;
for (int i=0; i<num.Length; i++)
{
// If the number itself contains a zero then
// decrement the counter
if (num[i] == '0')
{
non_zero--;
break;
}
// Adding the number of non zero numbers that
// can be formed
non_zero += (toInt(num[i])-1) * (int)(Math.Pow(9,k-1-i));
}
int no = 0, remaining = 0,calculatedUpto=0;
// Calculate the number and the remaining after
// ignoring the most significant digit
for (int i=0; i<num.Length; i++)
{
no = no*10 + (toInt(num[i]));
if (i != 0)
calculatedUpto = calculatedUpto*10 + 9;
}
remaining = no-calculatedUpto;
// Final answer is calculated
// It is calculated by subtracting 9....9 (d-1) times
// from no.
int ans = zeroUpto(k-1) + (remaining-non_zero-1);
return ans;
}
// Driver program to test the above functions
static public void Main() {
String num = "107";
Console.WriteLine("Count of numbers from 1" + " to "
+ num + " is " + countZero(num));
num = "1264";
Console.WriteLine("Count of numbers from 1" + " to "
+ num + " is " +countZero(num));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Modified javascript program to count number from 1 to n with
// 0 as a digit.
// Returns count of integers having zero upto given digits
function zeroUpto(digits)
{
// Refer below article for details
// https://www.geeksforgeeks.org/dsa/count-positive-integers-0-digit/
var first = parseInt( ((Math.pow(10,digits)-1)/9));
var second = parseInt( ((Math.pow(9,digits)-1)/8));
return 9 * (first - second);
}
// utility function to convert character representation
// to integer
function toInt(c)
{
return parseInt((c.charCodeAt(0))-48);
}
// counts numbers having zero as digits upto a given
// number 'num'
function countZero(num)
{
// k denoted the number of digits in the number
var k = num.length;
// Calculating the total number having zeros,
// which upto k-1 digits
var total = zeroUpto(k-1);
// Now let us calculate the numbers which don't have
// any zeros. In that k digits upto the given number
var non_zero = 0;
for (i=0; i<num.length; i++)
{
// If the number itself contains a zero then
// decrement the counter
if (num.charAt(i) == '0')
{
non_zero--;
break;
}
// Adding the number of non zero numbers that
// can be formed
non_zero += (toInt(num.charAt(i))-1) * (Math.pow(9,k-1-i));
}
var no = 0, remaining = 0,calculatedUpto=0;
// Calculate the number and the remaining after
// ignoring the most significant digit
for (i=0; i<num.length; i++)
{
no = no*10 + (toInt(num.charAt(i)));
if (i != 0)
calculatedUpto = calculatedUpto*10 + 9;
}
remaining = no-calculatedUpto;
// Final answer is calculated
// It is calculated by subtracting 9....9 (d-1) times
// from no.
var ans = zeroUpto(k-1) + (remaining-non_zero-1);
return ans;
}
// Driver program to test the above functions
var num = "107";
document.write("Count of numbers from 1" + " to "
+ num + " is " + countZero(num));
var num = "1264";
document.write("<br>Count of numbers from 1" + " to "
+ num + " is " +countZero(num));
// This code is contributed by shikhasingrajput
</script>
PHP
<?php
// PHP program to count
// number from 1 to n
// with 0 as a digit.
// Returns count of integers
// having zero upto given digits
function zeroUpto($digits)
{
$first = (int)((pow(10,
$digits) - 1) / 9);
$second = (int)((pow(9,
$digits) - 1) / 8);
return 9 * ($first - $second);
}
// counts numbers having
// zero as digits upto a
// given number 'num'
function countZero($num)
{
// k denoted the number
// of digits in the number
$k = strlen($num);
// Calculating the total
// number having zeros,
// which upto k-1 digits
$total = zeroUpto($k-1);
// Now let us calculate
// the numbers which don't
// have any zeros. In that
// k digits upto the given
// number
$non_zero = 0;
for ($i = 0;
$i < strlen($num); $i++)
{
// If the number itself
// contains a zero then
// decrement the counter
if ($num[$i] == '0')
{
$non_zero--;
break;
}
// Adding the number of
// non zero numbers that
// can be formed
$non_zero += (($num[$i] - '0') - 1) *
(pow(9, $k - 1 - $i));
}
$no = 0;
$remaining = 0;
$calculatedUpto = 0;
// Calculate the number
// and the remaining after
// ignoring the most
// significant digit
for ($i = 0;
$i < strlen($num); $i++)
{
$no = $no * 10 + ($num[$i] - '0');
if ($i != 0)
$calculatedUpto = $calculatedUpto *
10 + 9;
}
$remaining = $no - $calculatedUpto;
// Final answer is calculated
// It is calculated by subtracting
// 9....9 (d-1) times from no.
$ans = zeroUpto($k - 1) +
($remaining -
$non_zero - 1);
return $ans;
}
// Driver Code
$num = "107";
echo "Count of numbers from 1 to " .
$num . " is " .
countZero($num) . "\n";
$num = "1264";
echo "Count of numbers from 1 to " .
$num . " is " .
countZero($num);
// This code is contributed
// by mits
?>
Output:
Count of numbers from 1 to 107 is 17
Count of numbers from 1 to 1264 is 315
Complexity Analysis:
Time Complexity : O(d), where d is no. of digits i.e., O(log(n)
Auxiliary Space : O(1)
Approach#2: Using for loop
This code defines a function count_zeros_brute_force that takes an integer n as input and counts the number of integers from 1 to n that have the digit 0. The function simply iterates over all integers from 1 to n and checks if the string representation of each integer contains the character '0'. If it does, the count is incremented.The code then calls the function count_zeros_brute_force twice with different values of n and prints the results.
Algorithm
1. Initialize a counter variable to 0.
2. Traverse from 1 to n and for each number check if it has 0 in it.
3. If the number has 0, increment the counter variable.
4. Return the counter variable as the output.
C++
#include <string> // for string data type
#include <iostream>
int count_zeros_brute_force(int n) {
int count = 0; // initialize count variable to 0
for (int i = 1; i <= n; i++) { // loop through numbers 1 to n (inclusive)
if (std::to_string(i).find('0') != std::string::npos) {
// convert i to string and check if it contains '0'
count++; // increment count if '0' is found in i
}
}
return count; // return the final count
}
int main() {
int n = 107;
std::cout << count_zeros_brute_force(n) << std::endl; // output: 17
n = 1264;
std::cout << count_zeros_brute_force(n) << std::endl; // output: 315
return 0;
}
Java
public class CountZeros {
// Function to count the number of integers from 1 to n (inclusive) that contain the digit '0'
static int countZerosBruteForce(int n) {
int count = 0; // Initialize a count variable to 0
for (int i = 1; i <= n; i++) { // Loop through numbers from 1 to n (inclusive)
if (String.valueOf(i).contains("0")) {
// Convert i to a string and check if it contains the character '0'
count++; // Increment count if '0' is found in i
}
}
return count; // Return the final count
}
public static void main(String[] args) {
int n = 107;
System.out.println(countZerosBruteForce(n)); // Output: 17
n = 1264;
System.out.println(countZerosBruteForce(n)); // Output: 315
}
}
Python3
def count_zeros_brute_force(n):
count = 0
for i in range(1, n+1):
if '0' in str(i):
count += 1
return count
n=107
print(count_zeros_brute_force(n))
n=1264
print(count_zeros_brute_force(n))
C#
using System;
class Program
{
// Function to count the number of zeros in numbers from 1 to n (inclusive)
static int CountZerosBruteForce(int n)
{
int count = 0; // Initialize count variable to 0
// Loop through numbers 1 to n (inclusive)
for (int i = 1; i <= n; i++)
{
// Convert i to string and check if it contains '0'
if (i.ToString().Contains('0'))
{
count++; // Increment count if '0' is found in i
}
}
return count; // Return the final count
}
static void Main()
{
int n = 107;
Console.WriteLine(CountZerosBruteForce(n)); // Output: 17
n = 1264;
Console.WriteLine(CountZerosBruteForce(n)); // Output: 315
}
}
JavaScript
function countZerosBruteForce(n) {
let count = 0;
for (let i = 1; i <= n; i++) {
if (i.toString().includes('0')) {
// convert i to string and check if it includes '0'
count++;
}
}
return count;
}
let n = 107;
console.log(countZerosBruteForce(n)); // output: 17
n = 1264;
console.log(countZerosBruteForce(n)); // output: 315
Time Complexity: O(nlogn) for converting integer to string.
Space Complexity: O(1)
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