Intermediate Level
Implement the openLockMinimumTurnsSimple method that returns the minimum turns needed to reach the lock target.
The input contains a target lock code target. The lock starts at 0000, and each move turns one wheel one step forward or backward.
Digits wrap around, so moving backward from 0 gives 9, and moving forward from 9 gives 0.
Your task is to return the minimum number of turns needed to reach the target code.
Example 1
Input
target (string) =
9Returns (int)
1Example 2
Input
target (string) =
0Returns (int)
0Example 3
Input
target (string) =
10Returns (int)
1Since there are no blocked codes in this simplified version, each wheel can be solved independently.
For each digit, calculate the forward distance from 0 and the backward distance through wrap-around. The minimum moves for that wheel is min(digit, 10 - digit).
Add the minimum moves for all four digits to get the final answer.
Pseudocode:
function openLockMinimumTurnsSimple(target):
totalMoves = 0
for each digit character ch in target:
digit = numeric value of ch
clockwise = digit
anticlockwise = 10 - digit
totalMoves = totalMoves + minimum(clockwise, anticlockwise)
return totalMovesReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run