788. Rotated Digits 旋转数字

[抄题]:

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.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

至少包括一个2/5/6/9,不能有3/4/7

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

滥竽充数的一道题

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int rotatedDigits(int N) {
        //cc
        if (N == 0) {
            return 0;
        }
        //ini
        int count = 0;
        //for loop
        for (int i = 1; i <= N; i++) {
            if (isValid(i)) {
                count++;
            }
        }
        //return
        return count;
    }
    
    public boolean isValid(int i) {
        boolean trueState = false;
        
        while (i != 0) {
            if (i % 10 == 2) trueState = true;
            if (i % 10 == 5) trueState = true;
            if (i % 10 == 6) trueState = true;
            if (i % 10 == 9) trueState = true;
            if (i % 10 == 3) return false;
            if (i % 10 == 4) return false;
            if (i % 10 == 7) return false;
            i = i / 10;
        }
        
        //return 
        return trueState;
    }
}
View Code

 

posted @ 2018-03-26 09:57  苗妙苗  阅读(167)  评论(0编辑  收藏  举报