Given a number . Reduce this number to zero by subtracting the number by it’s most significant digit(Left most digit) at every step. The task is to count the number of steps it takes to be reduced to zero.
Input: 14 Output: 6 Steps: 14 - 1 = 13 13 - 1 = 12 12 - 1 = 11 11 - 1 = 10 10 - 1 = 9 9 - 9 = 0 Input: 20 Output: 12 Numbers after series of steps: 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 0
Naive Approach: A naive approach is to reduce the number by its first digit step-wise and find the count of steps, but the time complexity will be huge if a large number is provided.
Efficient Approach: The main idea of the efficient approach is to reduce the number of steps in the naive approach. We can skip the steps whose leading digits are the same in consecutive numbers, and count them. The algorithm of skipping those numbers with same leading digits is as follows:
- Let the number be last, count the digits in last and reduce it by 1, because the smallest number with same leading digit with same count of digits will have that number of zeros in it.
- Find the first digit of number of last, by last/count.
- Hence the smallest number of same number of count of digits with same leading number will be [first digit * (count-1)]
- the number of steps skipped can be achieved by [(last-smallest number)/first digit].
- Hence the next number last will be last – (first*skipped)
Below is the implementation of the above approach:
- Count number of step required to reduce N to 1 by following certain rule
- Program to make Indian Flag in Python | Step by Step
- Minimum sum after subtracting multiples of k from the elements of the array
- Check if it is possible to get back to 12'0 clock only by adding or subtracting given seconds
- Count of Numbers in Range where first digit is equal to last digit of the number
- Minimum step to reach one
- Reach A and B by multiplying them with K and K^2 at every step
- Count 'd' digit positive integers with 0 as a digit
- Largest number less than N with digit sum greater than the digit sum of N
- Minimum sum of the elements of an array after subtracting smaller elements from larger
- Count n digit numbers not having a particular digit
- Check if frequency of each digit is less than the digit
- Round-off a number to a given number of significant digits
- Find maximum operations to reduce N to 1
- Reduce the array to a single element with the given operation
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.