You are given a lock which is made up of n-different circular rings and each ring has 0-9 digit printed serially on it. Initially all n-rings together show a n-digit integer but there is particular code only which can open the lock. You can rotate each ring any number of time in either direction. You have to find the minimum number of rotation done on rings of lock to open the lock.
Input : Input = 2345, Unlock code = 5432 Output : Rotations required = 8 Explanation : 1st ring is rotated thrice as 2->3->4->5 2nd ring is rotated once as 3->4 3rd ring is rotated once as 4->3 4th ring is rotated thrice as 5->4->3->2 Input : Input = 1919, Unlock code = 0000 Output : Rotations required = 4 Explanation : 1st ring is rotated once as 1->0 2nd ring is rotated once as 9->0 3rd ring is rotated once as 1->0 4th ring is rotated once as 9->0
For a single ring we can rotate it in any of two direction forward or backward as:
But we are concerned with minimum number of rotation required so we should choose min (abs(a-b), 10-abs(a-b)) as a-b denotes the number of forward rotation and 10-abs(a-b) denotes the number of backward rotation for a ring to rotate from a to b. Further we have to find minimum number for each ring that is for each digit. So starting from right most digit we can easily the find minimum number of rotation required for each ring and end up at left most digit.
Minimum Rotation = 12
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum steps to come back to starting point in a circular tour
- Count rotations of N which are Odd and Even
- Count rotations divisible by 4
- Generate all rotations of a number
- Count rotations divisible by 8
- Generating numbers that are divisor of their right-rotations
- Check whether all the rotations of a given number is greater than or equal to the given number or not
- Circular primes less than n
- Largest right circular cylinder within a cube
- Largest right circular cylinder within a frustum
- Check whether a number is circular prime or not
- Longest rod that can be inserted within a right circular cylinder
- Permutations to arrange N persons around a circular table
- Maximize sum of consecutive differences in a circular array
- Time taken by two persons to meet on a circular track