leetcode#788. Rotated Digits

788. Rotated Digits

Problem Description

X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

Now given a positive number N, how many numbers X from 1 to N are good?

Solution

对每一个输入n,只要遍历一遍0-N检查每一个数是否选择合法即可。由于N的范围是0-10000,所以这样暴力求解时间复杂度并不高。
Easy!

class Solution {
public:
    int rotatedDigits(int N) {
        int num = 0;
        for (int i=0; i<=N; i++) {
            num += isValid(i) ? 1 : 0;
        }
        return num;
    }

    bool isValid(int n) {
        bool flag = false;
        while (n > 0) {
            switch (n % 10) {
                case 3: case 4: case 7: return false;
                case 1: case 0: case 8: break;
                default: flag = true;
            }
            n /= 10;
        }
        return flag;
    }
};

你可能感兴趣的:(leetcode)