// 演算法和 C 版相同；改用 std::string 把數字轉成字串，逐字元檢查。
// Same algorithm; we convert x to a std::string and scan characters.
// 這樣示範一些 C++ 慣用法：to_string、range-for、bool 旗標。
// Demonstrates idiomatic C++ features: to_string, range-based for, bool flags.

#include <string>     // 引入 std::string / for std::string and std::to_string
using namespace std;

class Solution {
public:
    int rotatedDigits(int n) {
        int count = 0;                              // 好數計數 / counter for good numbers
        for (int x = 1; x <= n; ++x) {              // 枚舉 [1, n] / loop through every candidate
            string s = to_string(x);                // 把整數轉成字串，例如 25 -> "25" / int -> string conversion
            bool valid = true;                      // 是否每位都能合法旋轉 / true while no invalid digit found
            bool changed = false;                   // 是否至少一位會改變 / true once we see a {2,5,6,9}
            for (char c : s) {                      // range-for：逐字元遍歷字串 / iterate over each character of s
                if (c == '3' || c == '4' || c == '7') {  // 比較字元用單引號 / chars are compared with single quotes
                    valid = false;                  // 出現非法字元 / invalid digit detected
                    break;                          // 立刻跳出迴圈 / no need to scan further
                }
                if (c == '2' || c == '5' || c == '6' || c == '9') {  // 旋轉後會變的位 / digits that change under rotation
                    changed = true;                 // 標記至少有一位會變 / mark that x will differ after rotation
                }
                // '0', '1', '8' 旋轉後不變，不需要旗標 / '0','1','8' rotate to themselves — no flag needed
            }
            if (valid && changed) ++count;          // 同時成立才計入 / both conditions must hold
        }
        return count;                               // 回傳答案 / return result
    }
};
