1088. 易混淆数 II
易混淆数(Confusing Number)指的是一个数字在整体旋转 180°
以后,能够得到一个和原来 不同 的数,且 新数字的每一位都应该是有效的。
本题我们会将数字旋转 180°
来生成一个新的数字。
- 当
0、1、6、8、9
旋转180°
以后,我们得到的新数字分别为 0、1、9、8、6。 - 当
2、3、4、5、7
旋转180°
后,是无法得到任何数字的。
请注意,在旋转一个数字之后,我们可以忽略前导零。
- 例如,在旋转
8000
之后,我们有0008
,它被认为只是8
。
给出正整数 n
,请你返回 [1, n]
范围内的 易混淆数 的数量 。
示例 1:
输入:n = 20 输出:6 解释:易混淆数为 [6,9,10,16,18,19]。 6 转换为 9 9 转换为 6 10 转换为 01 也就是 1 16 转换为 91 18 转换为 81 19 转换为 61
示例 2:
输入:n = 100 输出:19 解释:易混淆数为 [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100]。
提示:
-
1 <= n <= 10^9
做题结果
成功,就无脑暴力罗列所有结果,进行校验即可
方法:BFS
1. 9以内的,6以上返回1否则返回0
2. 其他情况把1,6,8,9罗列,逐个追加尾部即可,注意超出最大值的不继续处理
3. 校验逻辑
- 把整个数字根据映射翻过来,看看是否和源数字是否相同
- 相同则不是混淆数,不加入答案, 但是可以继续追加
- 不相同则可放入答案中,答案数+1,可以继续追加
class Solution {
public int confusingNumberII(int n) {
if(n<9) return n>=6?1:0;
Queue<Long> queue = new LinkedList<>();
int[] arr = new int[]{0, 1, 6, 8, 9};
queue.offer(1L);
queue.offer(6L);
queue.offer(8L);
queue.offer(9L);
int ans = 0;
Map<Integer,Integer> map = new HashMap<>();
map.put(0,0);
map.put(1,1);
map.put(6,9);
map.put(8,8);
map.put(9,6);
while (!queue.isEmpty()) {
long curr = queue.poll();
if (isConfuse(map,curr)) {
//System.out.println(curr);
++ans;
}
for (int v : arr) {
long next = curr*10+v;
if(next<=n) queue.offer(next);
}
}
return ans;
}
private boolean isConfuse(Map<Integer,Integer> map,long v){
long copy = v;
long reverse = 0;
while (copy>0){
int last = (int) (copy%10);
reverse = reverse*10+map.get(last);
copy = copy/10;
}
return v!=reverse;
}
}