VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-integer-divisible-by-9-after-inserting-any-digit-in-n/

⇱ Largest integer divisible by 9 after inserting any digit in N - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest integer divisible by 9 after inserting any digit in N

Last Updated : 16 Jun, 2022

Given a large integer N, the task is to find the largest possible integer which is divisible by 9 after inserting exactly one digit from 0 to 9 anywhere in the N.

Note: Leading zeroes are not allowed.

Examples:

Input: N = "12"
Output: 612
Explanation: The numbers which are divisible by 9 after inserting digit are 612, 162, 126.
And the largest integer is 612. So the output is 612

Input: N = "1346182944512412414214"
Output: 81346182944512412414214

Approach: The problem can be solved with the help of the below observation:

The idea is to insert the digit 0 to 9 at every position in the N and check is it divisible by 9 (divisible only if sum of digits is divisible by 9). 
If it is found to be true then store the maximum value with position where digit is inserted and finally print the maximum value. 

Follow the below steps to solve the problem:

  • Initialize a pair variable, ( say maxi = {"", 0}) to store the largest integer which is divisible by 9 with the position where the digit is inserted.
  • Iterate over the range [0, len) and calculate the digit sum of the number (say stored in variable sum).
  • Iterate over the range [0, len) and perform the following steps:
    •  Iterate for ch = '0' to '9' and perform the following steps:
      • Check for leading 0s, if it is found to be true then continue with the iteration.
      • Check if (ch - '0') + sum is divisible by 9 (i.e. sum after inserting that digit in N). If it is found to be true then set or update the value of maxi to the new value.
  • Finally, print the value of the maximum number (stored in maxi.first).

Below is the implementation of the above approach:


Output
612

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

Comment
Article Tags: