Back

4070 - Minimum Rotations to Dial a Number I

Description (leetcode)

You are given a string s of length 10 consisting of digits.

The dial contains the digits 0 through 9 in order and is circular, so 0 and 9 are adjacent. The pointer initially points to 0.

To dial each digit of s in order, rotate the pointer until it points to that digit. Each rotation moves the pointer to an adjacent digit, and you may rotate in either direction. Dialing a digit that the pointer already points to requires no rotations.

Return the minimum total number of rotations needed to dial every digit of s.

Example 1:

Input: s = “0192837465”

Output: 25

Explanation:

StepFromToRotations
1000
2011
3192
4923
5284
6835
7374
8743
9462
10651

The total is 0 + 1 + 2 + 3 + 4 + 5 + 4 + 3 + 2 + 1 = 25, which is the minimum total number of rotations.

Example 2:

Input: s = “1200210200”

Output: 12

Explanation:

StepFromToRotations
1011
2121
3202
4000
5022
6211
7101
8022
9202
10000

The total is 1 + 1 + 2 + 0 + 2 + 1 + 1 + 2 + 2 + 0 = 12, which is the minimum total number of rotations.

Constraints:

  • s.length == 10
  • s consists only of digits '0' to '9'

submission

click to reveal
use itertools::Itertools;

impl Solution {
    pub fn min_rotations(s: String) -> i32 {
        // leading zero trick
        std::iter::once(b'0')
            .chain(s.bytes())
            .tuple_windows() // requires itertools
            .map(|(a, b)| {
                let dis = a.abs_diff(b);
                i32::from(dis.min(10 - dis))
            })
            .sum()
    }
}