Confusing Number
Easy · Math & Geometry · Explanation and code example
Use the remainder
How it works
Instead of converting to a string, we can extract digits using modular arithmetic. Processing digits from right to left while building the rotated number from left to right naturally produces the reversed rotated version.
Steps
- Create a mapping of valid digits (
0,1,6,8,9) to their rotated values. - Make a copy of
nand initialize the rotated number to0. - Extract digits using modulo
10. If a digit is invalid, returnfalse. - Build the rotated number by multiplying by
10and adding the inverted digit. - Divide the copy by
10to move to the next digit. After processing all digits, compare the rotated number to the original.
Complexity
- Time complexity:
O(L) - Space complexity:
O(L)extra space used
Where
Lis the maximum number of digitsncan have.
Things to watch for
Confusing "Different" with "Invalid"
A confusing number must be valid (all digits can be rotated) AND look different after rotation. Returning true for invalid digits like 2, 3, 4, 5, 7 instead of returning false is incorrect.
Forgetting to Reverse After Inversion
Rotating 180 degrees means both inverting each digit AND reversing their order. Only inverting without reversing (or vice versa) gives the wrong result. For example, 69 inverts to 96 but must then reverse to 69, so 69 is NOT confusing.
Python code example
class Solution:
def confusingNumber(self, n: int) -> bool:
# Use 'invert_map' to invert each valid digit. Since we don't want to modify
# 'n', we create a copy of it as 'nCopy'.
invert_map = {0:0, 1:1, 8:8, 6:9, 9:6}
invert_number = 0
n_copy = n
# Get every digit of 'n_copy' by taking the remainder of it to 10.
while n_copy:
res = n_copy % 10
if res not in invert_map:
return False
# Append the inverted digit of 'res' to the end of 'rotated_number'.
invert_number = invert_number * 10 + invert_map[res]
n_copy //= 10
# Check if 'rotated_number' equals 'n'.
return invert_number != n
C++ code example
class Solution {
public:
bool confusingNumber(int n) {
// Use 'invertMap' to invert each valid digit. Since we don't want to modify
// 'n', we create a copy of it as 'nCopy'.
map<int, int> invertMap = {{0, 0}, {1, 1}, {6, 9}, {8, 8}, {9, 6}};
int rotatedNumber = 0, nCopy = n;
// Get every digit of 'nCopy' by taking the remainder of it to 10.
while (nCopy > 0) {
int res = nCopy % 10;
if (invertMap.find(res) == invertMap.end()) {
return false;
}
// Append the inverted digit of 'res' to the end of 'rotatedNumber'.
rotatedNumber = rotatedNumber * 10 + invertMap[res];
nCopy /= 10;
}
// Check if 'rotatedNumber' equals 'n'.
return rotatedNumber != n;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.