头像

带翅膀的猫

时光荏苒,我们一直都在

《LeetCode刷题(Easy Rank):788. Rotated Digits》

 3月前  •   LeetCode  •     •   20  •   0

Question:

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?

Example:

示例Input: 10
Output: 4
Explanation: 
There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.

Solution:

首先我们要了解如果一个数字含有3,4,7中的任意一个那么这个数字绝对不是符合题目规定的数字,然后在此基础上如果数字中含有2,5,6,7中的任意一个数字就是符合题目要求的数字。

JAVAclass Solution {
    public int rotatedDigits(int N) {
        // Good: 0, 1, 8; 2, 5; 6, 9; Bad: 3, 4, 7
        int res = 0;
        for (int i = 2; i <= N; i++) {
            if (valid(i)) {
                res++;
            }
        }
        return res;
    }
    
    private boolean valid(int num) {
        boolean flag = false;
        while (num > 0) {
            int digit = num % 10;
            if (digit == 3 || digit == 4 || digit == 7) {
                return false;
            }
            if (digit == 2 || digit == 5 || digit == 6 || digit == 9) {
                flag = true;
            }
            num /= 10;
        }
        return flag;
    }
}

 

上一篇:
下一篇:

 评论


 已有0条评论

    还没有任何评论,你来说两句吧!