Minimum number closest to N made up of odd digits only

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.

Examples:

Input: N = 725
Output: 719
Explanation:
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
Output: 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:



  1. If all the digits of N are odd, then print N as the answer.
  2. 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))
Auxiliary Space:O(1)

Efficient Approach: Follow the steps below to optimize the above approach:

  1. If all the digits of N are odd, then return N.
  2. 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.
  3. 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.
  4. Compare the absolute difference of the respective closest numbers obtained with N and print the one having least difference.
  5. If both the differences are found to be equal, print the smaller number.

Below is the implementation of the above approach:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to implement
# the above approach
  
# Function to return the smaller
# number closest to N made up of
# only odd digits
def closest_smaller(N):
  
    N = str(N)
  
    l = list(map(int, N))
    length = len(l)
      
    # Stores the position of
    # first even digit of N
    pos = -1
  
    # Iterate through each digit of N
    for i in range(length):
          
        # Check for even digit.
        if l[i] % 2 == 0:
            pos = i
            break
  
    # If the first even digit is 0
    if l[pos] == 0:
  
        # Replace 0 with 9
        l[pos] = 9
  
        # Iterate over preceding
        # digits
        for i in range(pos - 1, -1, -1):
  
            # If current digit is 1
            if l[i] == 1:
  
                # Check if it is the 
                # first digit or not
                if i == 0:
                      
                    # Append leading 0's
                    l[i] = 0
                    break
                      
                # Otherwise, replace by 9
                l[i] = 9
                  
            # Otherwise
            else:
  
                # Decrease its value by 2
                l[i] -= 2
                break
  
    # If the first even digit exceeds 0
    else:
          
        # Reduce the digit by 1
        l[pos] -= 1
  
    # Replace all succeeding digits by 9
    for i in range(pos + 1, length):
        l[i] = 9
  
    # Remove leading 0s
    if l[0] == 0:
        l.pop(0)
      
      
    result = ''.join(map(str, l))
    return result
      
# Function to return the greater
# number closest to N made up of
# only odd digits
def closest_greater(N):
  
    N = str(N)
  
    l = list(map(int, N))
    length = len(l)
  
    # Stores the position of
    # first even digit of N
    pos = -1
  
    # Iterate over each digit
    # of N
    for i in range(length):
          
        # If even digit is found
        if l[i] % 2 == 0:
            pos = i
            break
              
    # Increase value of first 
    # even digit by 1
    l[pos] += 1
  
    for i in range(pos + 1, length):
        l[i] = 1
  
    result = ''.join(map(str, l))
    return result
  
# Function to check if all 
# digits of N are odd or not
def check_all_digits_odd(N):
  
    N = str(N)
  
    l = list(map(int, N))
    length = len(l)
  
    # Stores the position of
    # first even digit of N
    pos = -1
  
    # Iterating over each digit
    # of N
    for i in range(length):
          
        # If even digit is found
        if l[i] % 2 == 0:
            pos = i
            break
              
    # If no even digit is found
    if pos == -1:
        return True
    return False
  
# Function to return the 
# closest number to N
# having odd digits only
def closestNumber(N):
      
    # If all digits of N are odd
    if check_all_digits_odd(N):
        print(N)
    else:
          
        # Find smaller number 
        # closest to N
        l = int(closest_smaller(N))
          
        # Find greater number 
        # closest to N
        r = int(closest_greater(N))
          
        # Print the number with least
        # absolute difference
        if abs(N - l) <= abs(N - r):
            print(l)
        else:
            print(r)
  
# Driver Code.
if __name__ == '__main__':
      
    N = 110
    closestNumber(N)
     

chevron_right


Output:

111

Time Complexity: O(len(N))
Auxiliary Space: O(len(N))

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.