Confusing Number
Problem
A confusing number is a number that, when rotated 180 degrees, becomes a different valid number. Each digit must remain a valid digit after rotation: 0→0, 1→1, 6→9, 8→8, 9→6. The digits 2, 3, 4, 5, 7 become invalid when rotated. Given an integer n, return true if n is a confusing number, otherwise false.
n = 6truedef confusing_number(n):
rot = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
original, rotated = n, 0
while n > 0:
d = n % 10
if d not in rot:
return False
rotated = rotated * 10 + rot[d]
n //= 10
return rotated != original
function confusingNumber(n) {
const rot = { 0: 0, 1: 1, 6: 9, 8: 8, 9: 6 };
const original = n;
let rotated = 0;
while (n > 0) {
const d = n % 10;
if (!(d in rot)) return false;
rotated = rotated * 10 + rot[d];
n = Math.floor(n / 10);
}
return rotated !== original;
}
class Solution {
public boolean confusingNumber(int n) {
int[] rot = { 0, 1, -1, -1, -1, -1, 9, -1, 8, 6 };
long original = n, rotated = 0;
while (n > 0) {
int d = n % 10;
if (rot[d] < 0) return false;
rotated = rotated * 10 + rot[d];
n /= 10;
}
return rotated != original;
}
}
bool confusingNumber(int n) {
int rot[10] = { 0, 1, -1, -1, -1, -1, 9, -1, 8, 6 };
long original = n, rotated = 0;
while (n > 0) {
int d = n % 10;
if (rot[d] < 0) return false;
rotated = rotated * 10 + rot[d];
n /= 10;
}
return rotated != original;
}
Explanation
A number is "confusing" if rotating it 180 degrees gives a different valid number. We build that rotated number digit by digit and compare it to the original.
The map rot says what each digit becomes upside down: 0→0, 1→1, 6→9, 8→8, 9→6. If we ever meet a digit not in this map (like 2, 3, 4, 5, 7), the rotation is invalid and we return false instantly.
We peel digits off the right with n % 10 and n //= 10. Building rotated = rotated * 10 + rot[d] as we go naturally reverses the digit order, which is exactly what a 180-degree flip does.
At the end we return rotated != original. The flipped number must be valid and different to count as confusing.
Example: n = 6. The only digit 6 maps to 9, so rotated = 9. Since 9 != 6, the function returns true.