Open In App

Minimum number closest to N made up of odd digits only

Improve
Improve
Like Article
Like
Save
Share
Report

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: 

C++




#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
// Function to return the smaller
// number closest to N made up of
// only odd digits
string closest_smaller(int N)
{
    string strN = to_string(N);
    vector<int> l(strN.length());
    for (int i = 0; i < strN.length(); i++) {
        l[i] = strN[i] - '0';
    }
    int length = l.size();
    int pos = -1;
    for (int i = 0; i < length; i++) {
        if (l[i] % 2 == 0) {
            pos = i;
            break;
        }
    }
    if (l[pos] == 0) {
        l[pos] = 9;
        for (int i = pos - 1; i >= 0; i--) {
            if (l[i] == 1) {
                if (i == 0) {
                    l[i] = 0;
                    break;
                }
                else {
                    l[i] = 9;
                }
            }
            else {
                l[i] -= 2;
                break;
            }
        }
    }
    else {
        l[pos] -= 1;
    }
    for (int i = pos + 1; i < length; i++) {
        l[i] = 9;
    }
    if (l[0] == 0) {
        l.erase(l.begin());
    }
    string result;
    for (int i = 0; i < l.size(); i++) {
        result += to_string(l[i]);
    }
    return result;
}
 
// Function to return the greater
// number closest to N made up of
// only odd digits
string closest_greater(int N)
{
    string strN = to_string(N);
    vector<int> l(strN.length());
    for (int i = 0; i < strN.length(); i++) {
        l[i] = strN[i] - '0';
    }
    int length = l.size();
    int pos = -1;
    for (int i = 0; i < length; i++) {
        if (l[i] % 2 == 0) {
            pos = i;
            break;
        }
    }
    l[pos] += 1;
    for (int i = pos + 1; i < length; i++) {
        l[i] = 1;
    }
    string result;
    for (int i = 0; i < l.size(); i++) {
        result += to_string(l[i]);
    }
    return result;
}
 
// Function to check if all
// digits of N are odd or not
bool check_all_digits_odd(int N)
{
    string strN = to_string(N);
    vector<int> l(strN.length());
    for (int i = 0; i < strN.length(); i++) {
        l[i] = strN[i] - '0';
    }
    int length = l.size();
    int pos = -1;
    for (int i = 0; i < length; i++) {
        if (l[i] % 2 == 0) {
            pos = i;
            break;
        }
    }
    if (pos == -1) {
        return true;
    }
    return false;
}
 
// Function to return the
// closest number to N
// having odd digits only
void closestNumber(int N)
{
    if (check_all_digits_odd(N)) {
 
        cout << N << endl;
    }
    else {
        int l = stoi(closest_smaller(N));
        int r = stoi(closest_greater(N));
        if (abs(N - l) <= abs(N - r)) {
            cout << l << endl;
        }
        else {
            cout << r << endl;
        }
    }
}
 
// Driver code
int main()
{
    int N = 110;
    closestNumber(N);
    return 0;
}


Java




// Java program for the above approach
 
import java.util.*;
 
public class GFG {
     
    // Function to return the smaller
    // number closest to N made up of
    // only odd digits
    static String ClosestSmaller(String n) {
        char[] digits = n.toCharArray();
        int length = digits.length;
     
        int pos = -1;
     
        for (int i = 0; i < length; i++) {
            if (digits[i] % 2 == 0) {
                pos = i;
                break;
            }
        }
     
        if (digits[pos] == '0') {
            digits[pos] = '9';
     
            for (int i = pos - 1; i >= 0; i--) {
                if (digits[i] == '1') {
                    if (i == 0) {
                        digits[i] = '0';
                        break;
                    }
     
                    digits[i] = '9';
                } else {
                    digits[i] = (char) (digits[i] - 2);
                    break;
                }
            }
        } else {
            digits[pos] = (char) (digits[pos] - 1);
        }
     
        for (int i = pos + 1; i < length; i++) {
            digits[i] = '9';
        }
     
        if (digits[0] == '0') {
            digits = Arrays.copyOfRange(digits, 1, digits.length);
        }
     
        String result = new String(digits);
        return result;
    }
     
    // Function to return the greater
    // number closest to N made up of
    // only odd digits
    static String ClosestGreater(String n) {
        char[] digits = n.toCharArray();
        int length = digits.length;
     
        int pos = -1;
     
        for (int i = 0; i < length; i++) {
            if (digits[i] % 2 == 0) {
                pos = i;
                break;
            }
        }
     
        digits[pos] = (char) (digits[pos] + 1);
     
        for (int i = pos + 1; i < length; i++) {
            digits[i] = '1';
        }
     
        String result = new String(digits);
        return result;
    }
     
    // Function to check if all
    // digits of N are odd or not
    static boolean CheckAllDigitsOdd(String n) {
        char[] digits = n.toCharArray();
        int length = digits.length;
     
        int pos = -1;
     
        for (int i = 0; i < length; i++) {
            if ((digits[i] - '0') % 2 == 0) {
                pos = i;
                break;
            }
        }
     
        if (pos == -1)
            return true;
     
        return false;
    }
         
    // Function to return the
    // closest number to N
    // having odd digits only
    static void ClosestNumber(String n) {
        if (CheckAllDigitsOdd(n)) {
            System.out.println(n);
        } else {
            int l = Integer.parseInt(ClosestSmaller(n));
     
            int r = Integer.parseInt(ClosestGreater(n));
     
            if (Math.abs(Integer.parseInt(n) - l)
                    < Math.abs(Integer.parseInt(n) - r)) {
                System.out.println(l);
            } else {
                System.out.println(r);
            }
        }
    }
    // Driver code
    public static void main(String[] args) {
        String n = "110";
        ClosestNumber(n);
    }
}
 
// This code is contributed by princekumaras


Python




# 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)
    


C#




using System;
 
class GFG
{
 
  // Function to return the smaller
  // number closest to N made up of
  // only odd digits
  static string ClosestSmaller(string n)
  {
    char[] digits = n.ToCharArray();
    int length = digits.Length;
 
    // Stores the position of
    // first even digit of N
    int pos = -1;
 
    // Iterate through each digit of N
    for (int i = 0; i < length; i++) {
      // Check for even digit.
      if (digits[i] % 2 == 0) {
        pos = i;
        break;
      }
    }
 
    // If the first even digit is 0
    if (digits[pos] == '0') {
      // Replace 0 with 9
      digits[pos] = '9';
 
      // Iterate over preceding
      // digits
      for (int i = pos - 1; i >= 0; i--) {
        // If current digit is 1
        if (digits[i] == '1') {
          // Check if it is the
          // first digit or not
          if (i == 0) {
            // Append leading 0's
            digits[i] = '0';
            break;
          }
 
          // Otherwise, replace by 9
          digits[i] = '9';
        }
        else {
          // Decrease its value by 2
          digits[i] = (char)(digits[i] - 2);
          break;
        }
      }
    }
    else {
      // If the first even digit exceeds 0,
      // reduce the digit by 1
      digits[pos] = (char)(digits[pos] - 1);
    }
 
    // Replace all succeeding digits by 9
    for (int i = pos + 1; i < length; i++) {
      digits[i] = '9';
    }
 
    // Remove leading 0s
    if (digits[0] == '0') {
      digits = digits[1..];
    }
 
    string result = new string(digits);
    return result;
  }
 
  // Function to return the greater
  // number closest to N made up of
  // only odd digits
  static string ClosestGreater(string n)
  {
    char[] digits = n.ToCharArray();
    int length = digits.Length;
 
    // Stores the position of
    // first even digit of N
    int pos = -1;
 
    // Iterate over each digit
    // of N
    for (int i = 0; i < length; i++) {
      // If even digit is found
      if (digits[i] % 2 == 0) {
        pos = i;
        break;
      }
    }
 
    // Increase value of first
    // even digit by 1
    digits[pos] = (char)(digits[pos] + 1);
 
    for (int i = pos + 1; i < length; i++) {
      digits[i] = '1';
    }
 
    string result = new string(digits);
    return result;
  }
 
  // Function to check if all
  // digits of N are odd or not
  static bool CheckAllDigitsOdd(string n)
  {
    char[] digits = n.ToCharArray();
    int length = digits.Length;
 
    // Stores the position of
    // first even digit of N
    int pos = -1;
 
    // Iterating over each digit
    // of N
    for (int i = 0; i < length; i++) {
      // If even digit is found
      if ((digits[i] - '0') % 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
  static void ClosestNumber(string n)
  {
    // If all digits of N are odd
    if (CheckAllDigitsOdd(n)) {
      Console.WriteLine(n);
    }
    else {
      // Find smaller number
      // closest to N
      int l = Convert.ToInt32(ClosestSmaller(n));
 
      // Find greater number
      // closest to N
      int r = Convert.ToInt32(ClosestGreater(n));
 
      // Print the number with least
      // absolute difference
      if (Math.Abs(Convert.ToInt32(n) - l)
          < Math.Abs(Convert.ToInt32(n) - r)) {
        Console.WriteLine(l);
      }
      else {
        Console.WriteLine(r);
      }
    }
  }
 
  static void Main(string[] args)
  {
    // Driver Code.
    string n = "110";
    ClosestNumber(n);
  }
}


Javascript




// JavaScript program to implement
// the above approach
 
// Function to return the smaller
// number closest to N made up of
// only odd digits
function closest_smaller(N) {
 
    N = N.toString();
 
    let l = N.split('').map(Number);
    let length = l.length;
 
    // Stores the position of
    // first even digit of N
    let pos = -1;
 
    // Iterate through each digit of N
    for (let i = 0; i < length; i++) {
 
        // 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 (let i = pos - 1; i >= 0; i--) {
 
            // 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;
 
            } else {
 
                // Decrease its value by 2
                l[i] -= 2;
                break;
            }
        }
    } else {
 
        // If the first even digit exceeds 0,
        // reduce the digit by 1
        l[pos] -= 1;
    }
 
    // Replace all succeeding digits by 9
    for (let i = pos + 1; i < length; i++) {
        l[i] = 9;
    }
 
    // Remove leading 0s
    if (l[0] === 0) {
        l.shift();
    }
 
    let result = l.join('');
    return result;
}
 
// Function to return the greater
// number closest to N made up of
// only odd digits
function closest_greater(N) {
 
    N = N.toString();
 
    let l = N.split('').map(Number);
    let length = l.length;
 
    // Stores the position of
    // first even digit of N
    let pos = -1;
 
    // Iterate over each digit
    // of N
    for (let i = 0; i < length; i++) {
 
        // 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 (let i = pos + 1; i < length; i++) {
        l[i] = 1;
    }
 
    let result = l.join('');
    return result;
}
 
// Function to check if all
// digits of N are odd or not
function check_all_digits_odd(N) {
 
    N = N.toString();
 
    let l = N.split('').map(Number);
    let length = l.length;
 
    // Stores the position of
    // first even digit of N
    let pos = -1;
 
    // Iterating over each digit
    // of N
    for (let i = 0; i < length; i++) {
 
        // 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
function closestNumber(N) {
     
    // If all digits of N are odd
    if (check_all_digits_odd(N))
        console.log(N)
    else {
        // Find smaller number
        // closest to N
        let l = parseInt(closest_smaller(N))
 
        // Find greater number
        // closest to N
        let r = parseInt(closest_greater(N))
 
        // Print the number with least
        // absolute difference
        if (Math.abs(N - l) < Math.abs(N - r))
            console.log(l)
        else
            console.log(r)
    }
}
 
// Driver Code.
let N = 110
closestNumber(N)
 
 
// by phasing17


Output:

111

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



Last Updated : 16 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads