Home > Enterprise >  Number of occurrences of digit in numbers from 0 to n
Number of occurrences of digit in numbers from 0 to n

Time:09-23

Given a number n, count number of occurrences of digits 0, 2 and 4 including n.

Example1:

n = 10
output: 4

Example2:
n = 22
output: 11

My Code:

n = 22

def count_digit(n):
    count = 0
    for i in range(n 1):
        if '2' in str(i):
            count  = 1
        if '0' in str(i):
            count  = 1
        if '4' in str(i):
            count  = 1
    return count

count_digit(n)

Code Output: 10

Desired Output: 11

Constraints: 1 <= N <= 10^5

Note: The solution should not cause outOfMemoryException or Time Limit Exceeded for large numbers.

CodePudding user response:

There are numbers in which the desired number is repeated, such as 20 or 22, so instead of adding 1 you must add 2

>>> 
>>> string = ','.join(map(str,range(23)))
>>> 
>>> string
'0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22'
>>> 
>>> string.count('0')   string.count('2')   string.count('4')
11
>>> 



n = 22

def count_digit(n):
    count = 0
    for i in map(str,range(n 1)):

        count =i.count('0')
        count =i.count('2')
        count =i.count('3')
    return count
print(count_digit(n))

CodePudding user response:

You can increment your count like this:

def count_digit(n):
    count = 0
    for i in range(n   1):
        if '2' in str(i):
            count  = str(i).count('2')
        if '0' in str(i):
            count  = str(i).count('0')
        if '4' in str(i):
            count  = str(i).count('4')
    return count

In that way, edge cases like 22, 44, and so on are covered!

  • Related