• 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.
    

    Note:

    • N  will be in range [1, 10000].

    将一个数字的每一位旋转180度,如果跟之前的数字不一样则是有效的

    统计1到N中有多少这样的数字

    3,4,7旋转后是无效的

    C++(5ms):

     1 class Solution {
     2 public:
     3     int rotatedDigits(int N) {
     4         int res = 0 ;
     5         for(int i = 1 ; i <= N ; i++){
     6             if (isValid(i)){
     7                 res++ ;
     8             }
     9         }
    10         return res ;
    11     }
    12     
    13     bool isValid(int n){
    14         bool flag = false ;
    15         while(n > 0){
    16             if (n % 10 == 2) flag = true ;
    17             if (n % 10 == 5) flag = true ;
    18             if (n % 10 == 6) flag = true ;
    19             if (n % 10 == 9) flag = true ;
    20             if (n % 10 == 3) return false ;
    21             if (n % 10 == 4) return false ;
    22             if (n % 10 == 7) return false ;
    23             n /= 10 ;
    24         }
    25         return flag ;
    26     }
    27 };
  • 相关阅读:
    桌面应用程序ClickOne打包部署
    Linux系统基础5周入门精讲(Linux发展过程)
    Linux系统基础5周入门精讲(服务器介绍)
    算法进阶--动态规划
    行为型模式
    结构型模式
    设计模式
    哈希表--树
    数据结构
    查找排序相关面试题
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8538780.html
Copyright © 2020-2023  润新知