Related Articles

# Count numbers having 0 as a digit

• Difficulty Level : Medium
• Last Updated : 19 Apr, 2021

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:

1. Count of 0 digit integers having maximum of d-1 digits.
2. 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:

1. 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)
2. 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 ``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/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

## 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/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

## 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/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

## PHP

 ``

## Javascript

 ``

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)

This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
{"ft_lang_label":"__label__en","ft_lang_prob":0.6636636,"math_prob":0.98579115,"size":14279,"snap":"2021-31-2021-39","text_gpt3_token_len":4308,"char_repetition_ratio":0.16672504,"word_repetition_ratio":0.44489646,"special_character_ratio":0.34589258,"punctuation_ratio":0.14227642,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99987495,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-08-02T20:54:23Z\",\"WARC-Record-ID\":\"<urn:uuid:0eb6c825-a6c6-4fd5-8394-a35013e14c4c>\",\"Content-Length\":\"198354\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:b75b3dc7-9e10-4189-a3af-a95db33dfcef>\",\"WARC-Concurrent-To\":\"<urn:uuid:60706e5e-e4a3-43cf-8068-c4558fb25298>\",\"WARC-IP-Address\":\"23.62.230.157\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/count-numbers-having-0-as-a-digit/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:UQZICI2NO26ITSGDWNQNOJBYL6RH6N7H\",\"WARC-Block-Digest\":\"sha1:AEEFARUV2FM5FHJN2K4NCLBGLTKRKX2A\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-31/CC-MAIN-2021-31_segments_1627046154385.24_warc_CC-MAIN-20210802203434-20210802233434-00007.warc.gz\"}"}