Given two numbers N and D. The task is to find out the largest number smaller than or equal to N which contains the maximum number of trailing nines and the difference between N and the number should not be greater than D.
Input: N = 1029, D = 102 Output: 999 1029 has 1 trailing nine while 999 has three trailing nine.Also 1029-999 = 30(which is less than 102). Input: N = 10281, D = 1 Output: 10281
A naive approach will be to iterate from N till N-D and find the number with the largest number of trailing nines.
An efficient approach can be found by some key observations. One key observation for this problem is that the largest number smaller than N ending with at least say(K) nines is
[n – (n MOD 10^k) – 1]
Traverse all possible values of k starting from total no of digits of N to 1, and check whether d > n%. If no such value is obtained, the final answer will be N itself. Otherwise, check for the answer using the above observation.
Below is the implementation of the above approach.
Time Complexity:O(no of digits)
- Largest even digit number not greater than N
- Largest number not greater than N all the digits of which are odd
- Largest number not greater than N which can become prime after rearranging its digits
- Largest number less than N with digit sum greater than the digit sum of N
- Count number of trailing zeros in Binary representation of a number using Bitset
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Largest subsequence having GCD greater than 1
- Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*..
- Trailing number of 0s in product of two factorials
- Number of trailing zeroes in base B representation of N!
- Count trailing zeroes in factorial of a number
- Smallest number with at least n trailing zeroes in factorial
- Smallest number divisible by n and has at-least k trailing zeros
- Find the smallest number X such that X! contains at least Y trailing zeros.
- Count number of trailing zeros in product of array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.