// 演算法 / Algorithm:
//   單次線性掃描。對每個字元，若其數值小於右鄰則減去，否則加上;
//   末字元永遠加。利用 switch 當查找表，常數空間。
//   Single linear pass: subtract a symbol if it's smaller than its right
//   neighbor, otherwise add it; the last symbol is always added.
//   A switch acts as the lookup table — constant space.

// 把單一羅馬字母轉成整數值 / Convert one Roman letter to its integer value.
static int val(char c) {
    // switch 依字元跳到對應分支 / switch jumps to the matching branch.
    switch (c) {
        case 'I': return 1;     // I = 1
        case 'V': return 5;     // V = 5
        case 'X': return 10;    // X = 10
        case 'L': return 50;    // L = 50
        case 'C': return 100;   // C = 100
        case 'D': return 500;   // D = 500
        case 'M': return 1000;  // M = 1000
        default:  return 0;     // 題目保證合法,理論上走不到 / unreachable by constraint
    }
}

int romanToInt(char* s) {
    int total = 0;              // 累積答案 / running total
    // 用標準函式 strlen 取得字串長度;LeetCode C 環境已包含 <string.h>
    // Use strlen() to get the length; <string.h> is included by LeetCode's harness.
    int n = (int)strlen(s);

    // 從第 0 個字元掃到最後一個 (索引 n-1) / iterate from index 0 to n-1.
    for (int i = 0; i < n; i++) {
        int cur = val(s[i]);    // 當前字元的數值 / value of current symbol

        // 若還有右鄰,且當前比右鄰小 → 減法配對的左邊一半
        // If there is a right neighbor and current < neighbor, this is a subtractive prefix.
        if (i + 1 < n && cur < val(s[i + 1])) {
            total -= cur;       // 減去當前值 / subtract it
        } else {
            total += cur;       // 否則加上 (含最後一個字元) / otherwise add (also covers last char)
        }
    }

    return total;               // 回傳結果 / return the accumulated value
}
