1. 程式人生 > >leetcode_788_旋轉數字

leetcode_788_旋轉數字

#define SAME 0 // 0, 1, 8
#define VALID 1 // 2, 6, 8, 9
#define INVALID 2 // 3, 4, 7
class Solution {
public:
    int rotatedDigits(int N) {
        int i, num, count = 0;
        int is_valid[] = { SAME, SAME, VALID, INVALID, INVALID, VALID, VALID, INVALID, SAME, VALID };//設定每個數字的結果
        bool found = false;//初始為false

        for (i = 2; i <= N; i++){
            num = i; found = false;//防止改動i和重置found
            while (num){
                if (is_valid[num % 10] == INVALID) { found = false; break; }//如果當前數字的個位數字為非法,found置為false,則直接跳出迴圈
                if (is_valid[num % 10] == VALID) found = true;//如果當前數字的個位數字合法,found置為true
                num = num / 10;//當前數字除以10,為了判斷高位
            }
            if (found == true) count++;//如果迴圈完後,仍然是合法,那證明這個數字是valid number
        }

        return count;
    }
};