Given an integer N, the task is to form a minimum possible positive number (>0) by inverting some digits of N.
Inverting for a digit T is defined as subtracting it from 9 that is 9 – T.
Note: The final number should not start from zero.
Input:N = 4545
The minimum possible number is 4444 by subtracting the two 5 ( 9 – 5 = 4)
Input: N = 9000
The minimum possible number is 9000 cause the number has to be > 0 and hence 9 cannot be subtracted from itself.
Approach: The idea is to iterate over all the digits in the given number and check if 9 – current_digit is less than the current_digit then replace that digit with 9 – current_digit else don’t change the digit. If the first digit of the number is 9 then don’t change the digit and we can’t have trailing zero in the new number formed.
Below is the implementation of the above approach:
Time Complexity: O(log10N)
Auxiliary Space: O(log10N)
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.
- Find smallest number with given number of digits and sum of digits under given constraints
- Find smallest number with given number of digits and sum of digits
- Total distinct pairs from two arrays such that second number can be obtained by inverting bits of first
- Smallest multiple of N formed using the given set of digits
- Minimum inverting factor in an array
- Check if all the elements can be made of same parity by inverting adjacent elements
- Maximum Subarray Sum after inverting at most two elements
- Number formed by deleting digits such that sum of the digits becomes even and the number odd
- Smallest number with given sum of digits and sum of square of digits
- Find maximum number that can be formed using digits of a given number
- Count of numbers upto N digits formed using digits 0 to K-1 without any adjacent 0s
- Find the largest number that can be formed with the given digits
- Find position of given term in a series formed with only digits 4 and 7 allowed
- Count numbers formed by given two digit with sum having given digits
- Find the smallest number whose digits multiply to a given number n
- Find smallest possible Number from a given large Number with same count of digits
- Find the Largest number with given number of digits and sum of digits
- Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
- Minimum digits to be removed to make either all digits or alternating digits same
- Find all strings formed from characters mapped to digits of a number
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.