Count numbers having 0 as a digit
Count how many integers from 1 to N contain 0’s 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.
The idea is to traverse all numbers from 1 to n. For every traversed number, traverse through its digits, if any digit is 0, increment count. Below is the implementation of the above idea :
C++
#include<bits/stdc++.h>
using namespace std;
int has0( int x)
{
while (x)
{
if (x % 10 == 0)
return 1;
x /= 10;
}
return 0;
}
int getCount( int n)
{
int count = 0;
for ( int i=1; i<=n; i++)
count += has0(i);
return count;
}
int main()
{
int n = 107;
cout << "Count of numbers from 1" << " to "
<< n << " is " << getCount(n);
}
|
Java
import java.io.*;
class GFG {
static int has0( int x)
{
while (x != 0 )
{
if (x % 10 == 0 )
return 1 ;
x /= 10 ;
}
return 0 ;
}
static int getCount( int n)
{
int count = 0 ;
for ( int i = 1 ; i <= n; i++)
count += has0(i);
return count;
}
public static void main(String args[])
{
int n = 107 ;
System.out.println( "Count of numbers from 1"
+ " to " +n + " is " + getCount(n));
}
}
|
Python3
def has0(x) :
while (x ! = 0 ) :
if (x % 10 = = 0 ) :
return 1
x = x / / 10
return 0
def getCount(n) :
count = 0
for i in range ( 1 , n + 1 ) :
count = count + has0(i)
return count
n = 107
print ( "Count of numbers from 1" , " to " ,
n , " is " , getCount(n))
|
C#
using System;
class GFG
{
static int has0( int x)
{
while (x != 0)
{
if (x % 10 == 0)
return 1;
x /= 10;
}
return 0;
}
static int getCount( int n)
{
int count = 0;
for ( int i = 1; i <= n; i++)
count += has0(i);
return count;
}
public static void Main()
{
int n = 107;
Console.WriteLine( "Count of numbers from 1"
+ " to " +n + " is " + getCount(n));
}
}
|
Javascript
<script>
function has0(x)
{
while (x)
{
if (x % 10 == 0)
return 1;
x = Math.floor(x / 10);
}
return 0;
}
function getCount(n)
{
let count = 0;
for (let i=1; i<=n; i++)
count += has0(i);
return count;
}
let n = 107;
document.write( "Count of numbers from 1" + " to "
+ n + " is " + getCount(n));
</script>
|
Output
Count of numbers from 1 to 107 is 17
Time Complexity: O(n log n)
Auxiliary Space: O(1)
Refer below post for an optimized solution.
Count numbers having 0 as a digit
Last Updated :
23 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...