// 演算法 / Algorithm:
// 暴力枚舉 [num1, num2] 內每個數，拆成數位後檢查每個中間數位是否為山峰或山谷，累加總數。
// Brute-force every number in [num1, num2]: split into digits, count peaks/valleys
// among the middle digits, and accumulate. n <= 1e5 so this is easily fast enough.

int totalWaviness(int num1, int num2) {
    int total = 0;                       // 累計所有數字的波動度 / running sum of waviness

    // 外層迴圈：枚舉區間內每一個整數 n / outer loop: every integer n in the range
    for (int n = num1; n <= num2; n++) {
        int digits[7];                   // 暫存數位，最多 6 位(1e5) 留一點餘裕 / buffer for digits
        int len = 0;                     // 目前數位個數 / how many digits stored so far

        // 用 %10 取最後一位、/10 去掉最後一位，逐位拆解 / extract digits one by one
        // 注意：這樣存進去是「反序」(低位在前)，但不影響峰谷計數 / stored reversed; count unaffected
        int t = n;                       // 用副本拆解，保留原本的 n / work on a copy so n stays intact
        while (t > 0) {
            digits[len] = t % 10;        // t % 10 取出最後一位數字 / lowest digit
            len = len + 1;               // 記錄又多了一位 / one more digit recorded
            t = t / 10;                  // 整數除法捨去最後一位 / drop the lowest digit
        }

        // 少於 3 位的數字波動度一定是 0，直接跳過 / fewer than 3 digits => waviness 0
        if (len < 3) continue;

        // 掃描每個「中間」數位：索引 1 到 len-2 (頭尾不算) / scan middle digits only
        for (int i = 1; i < len - 1; i++) {
            int left  = digits[i - 1];   // 左鄰居 / left neighbor
            int mid   = digits[i];       // 目前數位 / current digit
            int right = digits[i + 1];   // 右鄰居 / right neighbor

            // 山峰：嚴格大於兩鄰居 / peak: strictly greater than both neighbors
            if (mid > left && mid > right) {
                total = total + 1;       // 找到一個峰，波動度 +1 / one peak found
            }
            // 山谷：嚴格小於兩鄰居 / valley: strictly less than both neighbors
            else if (mid < left && mid < right) {
                total = total + 1;       // 找到一個谷，波動度 +1 / one valley found
            }
            // 其餘情況(含相等)不計 / everything else (including ties) contributes 0
        }
    }

    return total;                        // 回傳區間總波動度 / return the grand total
}
