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) = 9
Returns (int) 1

Example 2

Input
target (string) = 0
Returns (int) 0

Example 3

Input
target (string) = 10
Returns (int) 1

Since 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 totalMoves
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.