Leetcode-字符串-788

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.

A number is valid if each digit remains a digit after rotation. 0, 1, 8 rotate to themselves; 2, 5 rotate to each other; 6, 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?

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.

判断数字旋转180°后为非本身数字的个数

方法1:5ms

构建N+1的数组,对应存储每个数字的标记
2569对应标记words[i]=2,018对应标记words[i]=1
当i < 10时,i的标记值可直接确定
当i >= 10时,i的标记值直接由 i/10i%10 决定即可。由于i是从小到大依次运行的,所以可直接读取之前已经确定好的words[i / 10]和words[i % 10]。

public int rotatedDigits2(int N) {
        int[] words = new int[N + 1];
        int count = 0;
        for (int i = 0; i <= N; i++) {
            if (i < 10){
                if (i == 2 || i == 5 || i == 6 || i == 9) {
                    words[i] = 2;
                    count++;
                }
                else if (i == 0 || i == 1 || i == 8)
                    words[i] = 1;
            }
            else {
                int a = words[i / 10], b = words[i % 10];
                if (a == 1 && b == 1) words[i] = 1;
                else if (a >= 1 && b >= 1){
                    words[i] = 2;
                    count++;
                }
            }
        }
        return count;
}


方法2:6ms

通过%10,分别判断每一位的类型。
数字中只要一位是347,这个数字就不是“好数字”,跳过此次循环
数字中只要一位是2569,这个数字就是“好数字”,num++

public int rotatedDigits3(int N) {
        int num = 0;
        for (int i = 0; i <= N; i++) {
            boolean flag = false;
            int temp = i;
            while (temp != 0) {
                int val = temp % 10;
                if (val == 3 || val == 4 || val == 7) {
                    flag = false;
                    break;
                }
                else if (val == 2 || val == 5 || val == 6 || val == 9)
                    flag = true;
                temp = temp / 10;
            }
            if (flag) num++;
        }
        return num;
    }
}


方法3:19ms, 麻烦不推荐

通过先将数字转换成字符串,然后再分别判断每一位的类型。没必要转成字符串QAQ

public int rotatedDigits(int N) {
        String str1 = "018";
        String str2 = "2569";
        String str3 = "347";
        int num = 0;
        for (int i = 0; i <= N; i++) {
            boolean flag = false;
            for (char ch : Integer.toString(i).toCharArray()){
                if (str3.indexOf(ch) != -1){
                    flag = false;
                    break;
                }
                else if (str2.indexOf(ch) != -1) flag = true;
            }
            if (flag) num++;
        }
        return num;
}


猜你喜欢

转载自blog.csdn.net/gaoruowen1/article/details/80992965
今日推荐