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%
Below is the implementation of the above approach.
Time Complexity:O(no of digits)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Largest number less than N with digit sum greater than the digit sum of N
- Count of Array elements greater than or equal to twice the Median of K trailing Array elements
- Find Largest Special Prime which is less than or equal to a given number
- Largest number less than or equal to N/2 which is coprime to N
- Highest and Smallest power of K less than and greater than equal to N respectively
- 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
- Smallest subarray of size greater than K with sum greater than a given value
- Largest number less than N whose each digit is prime number
- Largest number M less than N such that XOR of M and N is even
- Sum of largest prime factor of each number less than equal to n
- Largest number less than or equal to Z that leaves a remainder X when divided by Y
- Count number of trailing zeros in Binary representation of a number using Bitset
- Count number of integers less than or equal to N which has exactly 9 divisors
- Count number less than N which are product of perfect squares
- Smallest number divisible by n and has at-least k trailing zeros
- C++ program to find all numbers less than n, which are palindromic in base 10 and base 2.
- Largest even digit number not greater than N
- Find largest factor of N such that N/F is less than K
- Largest subset having with sum less than equal to sum of respective indices
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.