Given an integer N, the task is to find the number closest to N having only odd digits. If more than one such number exists, print the minimum.
Input: N = 725
Numbers 719 and 731 consists of odd digits only and are closest to 725. Since 719 is the minimum, it is the required answer.
Input : N = 111
Naive Approach: The simplest approach to solve the problem is to iterate and find the closest numbers smaller and greater than N, having only odd numbers as its digits. Follow the steps below to solve the problem:
- If all the digits of N are odd, then print N as the answer.
- Find the closest smaller and greater numbers and return the one having the least difference with N. If both are found to be equidistant from N, print the smaller number.
Time Complexity: O(10(len(N) – 1))
Efficient Approach: Follow the steps below to optimize the above approach:
- If all the digits of N are odd, then return N.
- Calculate the closest smaller number to N efficiently by the following steps:
- Find the position of first even digit in N from left to right, i.e, pos.
- If the first even digit is 0, then replace 0 with 9 and iterate over all preceding digits and for every digit, if found to be 1, replace it with 9. Otherwise, decrease the digit by 2 and return the number.
- If no preceding digits are found to be exceeding 1, then replace the most significant digit with 0.
- If the first even digit is non-zero, then decrease that digit by 1. Replace all the succeeding digits with 9.
- Calculate the greater number closest to N by the steps below:
- Find the position of first even digit i.e pos.
- Increment the digits at pos by 1.
- Iterate over the succeeding digits and increment them by 1.
- Compare the absolute difference of the respective closest numbers obtained with N and print the one having least difference.
- If both the differences are found to be equal, print the smaller number.
Below is the implementation of the above approach:
Time Complexity: O(len(N))
Auxiliary Space: O(len(N))
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.