Count the number of occurrences of 0's in integers from 1 to N

Viewed 29297

How will you efficiently count number of occurrences of 0's in the decimal representation of integers from 1 to N?

e.g. The number of 0's from 1 to 105 is 16. How?

10,20,30,40,50,60,70,80,90,100,101,102,103,104,105    

Count the number of 0's & you will find it 16.

Obviously, a brute force approach won't be appreciated. You have to come up with an approach which doesn't depend on "How many numbers fall between 1 to N". Can we just do by seeing some kind of pattern?

Cannot we extend the logic compiled here to work for this problem?

7 Answers

I have a very simple way to do count 0's in between 1 to n. I hope this will solve your issue and remove complexity

function countZero(n) {
  var count = 0;
  while (n > 0) {
    count += Math.floor(n / 10);
    n = n / 10;
  }
  console.log(count);
}

countZero(99);
# in single loop without using inbuilt functions

def func(n):
  lst=list(range(0,n+1)) #make list from 0 to n

  strng=str(lst) #convert list into string

  strng=strng[1:-1] #remove first and last square braces from string

  strng=strng.replace(",","") #remove commas

  strng=strng.replace(" ","") #remove spaces

  #now this is the complete string from 0 to n number
  count=0
  num=0
  for i in strng:
    if i==str(num):
      count += 1
  print(count)
func(10)

#Azizullah Ali
Related