LeetCode 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]
题目标签:String
题目给了我们一个N, 让我们找出从 1 到 N 中有几个 good number。Good Number 是每一个digit 都可以旋转,然后旋转后 与 旋转前 是不同的 数字。
利用HashMap 把 0,1,8,2,5,6,9 这些可以旋转的数字存入保存。
之后利用Map来检查数字的每一个 digit 是否可以旋转,当旋转完之后的新数字 要与 旧数字 不同,才可以算。
具体请看code。
Java Solution:
Runtime beats 23.35%
完成日期:05/11/2018
关键词:HashMap
关键点:把可以旋转的digit存入map
1 class Solution 2 { 3 public int rotatedDigits(int N) 4 { 5 int count = 0; 6 HashMap<Integer, Integer> map = new HashMap<>(); 7 8 map.put(0, 0); 9 map.put(1, 1); 10 map.put(8, 8); 11 map.put(2, 5); 12 map.put(5, 2); 13 map.put(6, 9); 14 map.put(9, 6); 15 16 17 for(int i=1; i<=N; i++) 18 { 19 int number = i; 20 int newNumber = 0; 21 int m = 1; 22 23 while(number > 0) 24 { 25 int digit = number % 10; // get the digit 26 27 if(map.containsKey(digit)) // check if digit can be rotated 28 { 29 newNumber = map.get(digit) * m + newNumber; 30 number /= 10; 31 m *= 10; 32 } 33 else // if digit is invalid 34 { 35 break; 36 } 37 } 38 39 if(number == 0 && i != newNumber) 40 count++; 41 42 } 43 44 return count; 45 } 46 }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/