# 1056. Confusing Number

Given a number `N`, return `true` if and only if it is a  confusing number , which satisfies the following condition:

We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid. A  confusing number  is a number that when rotated 180 degrees becomes a different number with each digit valid.

Example 1:

``````Input: 6
Output: true
Explanation:
We get `9` after rotating `6`, `9` is a valid number and `9!=6`.
``````

Example 2:

``````Input: 89
Output: true
Explanation:
We get `68` after rotating `89`, `86` is a valid number and `86!=89`.
``````

Example 3:

``````Input: 11
Output: false
Explanation:
We get `11` after rotating `11`, `11` is a valid number but the value remains the same, thus `11` is not a confusing number.
``````

Example 4:

``````Input: 25
Output: false
Explanation:
We get an invalid number after rotating `25`.
``````

Note:

1. `0 <= N <= 10^9`
2. After the rotation we can ignore leading zeros, for example if after rotation we have `0008` then this number is considered as just `8`.

``````class Solution {
public:
bool confusingNumber(int N) {
int num = 0, oldN = N;
unordered_set<int> invalid{{2, 3, 4, 5, 7}};
while (N > 0) {
int digit = N % 10;
if (invalid.count(digit)) return false;
if (digit == 6) digit = 9;
else if (digit == 9) digit = 6;
num = num * 10 + digit;
N /= 10;
}
return num != oldN;
}
};
``````

``````class Solution {
public:
bool confusingNumber(int N) {
unordered_map<int, int> m{{0, 0}, {1, 1}, {6, 9}, {8, 8}, {9, 6}};
long oldN = N, res = 0;
while (N > 0) {
if (!m.count(N % 10)) return false;
res = res * 10 + m[N % 10];
N /= 10;
}
return res != oldN;
}
};
``````

``````class Solution {
public:
bool confusingNumber(int N) {
bool res = false;
vector<int> rotate{0, 1, -1, -1, -1, -1, 9, -1, 8, 6};
string str = to_string(N);
int n = str.size(), left = 0, right = n - 1;
while (left <= right) {
if (rotate[str[left] - '0'] == -1 || rotate[str[right] - '0'] == -1) return false;
if (rotate[str[left] - '0'] != (str[right] - '0')) res = true;
++left; --right;
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1056

Strobogrammatic Number

Confusing Number II

https://leetcode.com/problems/confusing-number/

https://leetcode.com/problems/confusing-number/discuss/303832/Java-Solution-using-HashMap-Similar-to-246.-Strobogrammatic-Number

https://leetcode.com/problems/confusing-number/discuss/398574/Java-0ms-12-line-solution-with-two-pointers

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation