Confusing Number
Map each digit to its 180-degree rotation; reject digits that have no rotation; check the rotated value differs from original.
Problem#
A confusing number, when rotated 180 degrees, becomes a different valid number. Digits 0, 1, 6, 8, 9 rotate to 0, 1, 9, 8, 6; the rest are invalid. Return true iff n is confusing.
Examples#
6→true(rotates to 9).89→true;11→false(rotates to itself);25→false.
Constraints#
0 <= n <= 10^9.
Approach#
Extract digits LSB first. If any digit is invalid, return false. Build the rotated number by prepending each rotated digit (mathematically: multiply running by 10 and add). Return rotated != n.
Solution#
class Solution {public: bool confusingNumber(int n) { int map[10] = {0,1,-1,-1,-1,-1,9,-1,8,6}; long long rot = 0, x = n; if (x == 0) return false; while (x > 0) { int d = x % 10; if (map[d] < 0) return false; rot = rot * 10 + map[d]; x /= 10; } return rot != n; }};func confusingNumber(n int) bool { digitMap := [10]int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6} if n == 0 { return false } rot, x := 0, n for x > 0 { d := x % 10 if digitMap[d] < 0 { return false } rot = rot*10 + digitMap[d] x /= 10 } return rot != n}class Solution: def confusingNumber(self, n: int) -> bool: digit_map = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6} if n == 0: return False rot, x = 0, n while x > 0: d = x % 10 if d not in digit_map: return False rot = rot * 10 + digit_map[d] x //= 10 return rot != nfunction confusingNumber(n) { const digitMap = { 0: 0, 1: 1, 6: 9, 8: 8, 9: 6 }; if (n === 0) return false; let rot = 0; let x = n; while (x > 0) { const d = x % 10; if (!(d in digitMap)) return false; rot = rot * 10 + digitMap[d]; x = Math.floor(x / 10); } return rot !== n;}class Solution { public boolean confusingNumber(int n) { int[] digitMap = {0, 1, -1, -1, -1, -1, 9, -1, 8, 6}; if (n == 0) return false; long rot = 0; long x = n; while (x > 0) { int d = (int) (x % 10); if (digitMap[d] < 0) return false; rot = rot * 10 + digitMap[d]; x /= 10; } return rot != n; }}function confusingNumber(n: number): boolean { const digitMap: Record<number, number> = { 0: 0, 1: 1, 6: 9, 8: 8, 9: 6 }; if (n === 0) return false; let rot = 0; let x = n; while (x > 0) { const d = x % 10; if (!(d in digitMap)) return false; rot = rot * 10 + digitMap[d]; x = Math.floor(x / 10); } return rot !== n;}Editorial#
Building the rotated value by rot * 10 + map[d] while peeling from the LSB correctly inverts digit order — the original’s LSB ends up as the rotated’s MSB, which is precisely what 180-degree rotation does. The valid-digit mask doubles as both check and translation table.
Complexity#
- Time:
O(log n). - Space:
O(1).
Concept revision#
Related#