Confusing Number

Map each digit to its 180-degree rotation; reject digits that have no rotation; check the rotated value differs from original.

Easy
Time O(log n) Space O(log n)
LeetCode
3 min read
math

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#

  • 6true (rotates to 9).
  • 89true; 11false (rotates to itself); 25false.

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#

Confusing Number
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;
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.