Given an integer N, the task is to reduce N to 1 with the following two operations:
- 1 can be subtracted from each of the digits of the number only if the digit is greater than 0 and the resultant number doesn’t have any leading 0s.
- 1 can be subtracted from the number itself.
The task is to find the minimum number of such operations required to reduce N to 1.
Input: N = 35
35 -> 24 -> 14 -> 13 -> 12 -> 11 -> 10 -> … -> 1 (14 operations)
Input: N = 240
Approach: It can be observed that if the number is power of 10 i.e. N = 10p then the number of operations will be (10 * p) – 1. For example, if N = 102 then operations will be (10 * 2) – 2 = 19
i.e. 100 -> 99 -> 88 -> 77 -> … -> 33 -> 22 -> 11 -> 10 -> 9 -> 8 -> … -> 2 -> 1.
Now, the task is to first convert the given to a power of 10 with the given operations and then count the number of operations required to reduce that power of 10 to 1. The sum of these operations is the required answer. The number of operations required to convert a number to a power of will be max(first_digit – 1, second_digit, third_digit, …, last_digit), this is because every digit can be reduced to 0 but the first digit must be 1 in order for it to be power of 10 with equal number of digits.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Minimum number of operations required to reduce N to 1
- Minimum number of given operations required to reduce the array to 0 element
- Reduce a number to 1 by performing given operations | Set 2
- Count the number of operations required to reduce the given number
- Reduce the number to minimum multiple of 4 after removing the digits
- Find maximum operations to reduce N to 1
- Count operations of the given type required to reduce N to 0
- Minimum prime number operations to convert A to B
- Minimum number operations required to convert n to m | Set-2
- Convert a number m to n using minimum number of given operations
- Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M
- Minimum number of operations on a binary string such that it gives 10^A as remainder when divided by 10^B
- Minimum number of increment/decrement operations such that array contains all elements from 1 to N
- Find minimum number of merge operations to make an array palindrome
- Find the minimum number of operations required to make all array elements equal
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.