前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LWC 73: 788. Rotated Digits

LWC 73: 788. Rotated Digits

作者头像
用户1147447
发布2019-05-26 08:55:29
2960
发布2019-05-26 08:55:29
举报
文章被收录于专栏:机器学习入门

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1434548

LWC 73: 788. Rotated Digits

传送门:788. Rotated Digits

Problem:

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, 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. Now given a positive number N, how many numbers X from 1 to N are good?

Example:

Input: 10 Output: 4 Explanation:undefined 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.

Note:

N will be in range 1, 10000.

思路:

观察N最大不超过10000,可以暴力解决。遍历1到N,核实每个num,如果num符合Rotated Digits则计数。

Java版本:

代码语言:javascript
复制
    public int rotatedDigits(int N) {
        int cnt = 0;
        for (int i = 1; i <= N; ++i) {
            int rotate = valid(i);
            if (rotate != -1 && rotate != i) cnt += 1;
        }
        return cnt;
    }

    public int valid(int n) {
        int[] map = {0, 1, 5, -1, -1, 2, 9, -1, 8, 6};
        int num = 0; int p = 1;
        for(;n != 0; n /= 10) {
            int digit = map[n % 10];
            if (digit == -1) return -1;
            num = num + p * digit;
            p *= 10;
        }
        return num;
    }

Python版本:

代码语言:javascript
复制
class Solution(object):
    def rotatedDigits(self, N):
        s1 = set([1, 8, 0])
        s2 = set([1, 2, 5, 8, 6, 9, 0])
        def isGood(n):
            s = set([int(i) for i in str(n)])
            return s.issubset(s2) and not s.issubset(s1)
        return sum(isGood(i) for i in range(N + 1))
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年02月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 73: 788. Rotated Digits
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档