Given a number n, write a function that returns count of numbers from 1 to n that don’t contain digit 3 in their decimal representation.
Input: n = 10 Output: 9 Input: n = 45 Output: 31 // Numbers 3, 13, 23, 30, 31, 32, 33, 34, // 35, 36, 37, 38, 39, 43 contain digit 3. Input: n = 578 Ouput: 385
We strongly recommend that you click here and practice it, before moving on to the solution.
We can solve it recursively. Let count(n) be the function that counts such numbers.
'msd' --> the most significant digit in n 'd' --> number of digits in n. count(n) = n if n < 3 count(n) = n - 1 if 3 <= n 10 and msd is not 3 count(n) = count( msd * (10^(d-1)) - 1) if n > 10 and msd is 3
Let us understand the solution with n = 578. count(578) = 4*count(99) + 4 + count(78) The middle term 4 is added to include numbers 100, 200, 400 and 500. Let us take n = 35 as another example. count(35) = count (3*10 - 1) = count(29)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Count numbers from 1 to n that have 4 as a digit
- Birthday Paradox
- Print all permutations in sorted (lexicographic) order
- Check divisibility by 7
- Given a number, find the next smallest palindrome
- Generate integer from 1 to 7 with equal probability
- Find day of the week for a given date
- Sieve of Eratosthenes
- Magic Square
- Average of a stream of numbers
- Program for Fibonacci numbers
- Write you own Power without using multiplication(*) and division(/) operators
- Print all combinations of points that can compose a given number
- Write a program to add two numbers in base 14
- Write an Efficient Method to Check if a Number is Multiple of 3
Improved By : Mithun Kumar