Confusing Number Problem
Description
LeetCode Problem 1056.
A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.
We can rotate digits of a number by 180 degrees to form new digits.
- When
0,1,6,8, and9are rotated180degrees, they become0,1,9,8, and6respectively. - When
2,3,4,5, and7are rotated180degrees, they become invalid.
Note that after rotating a number, we can ignore leading zeros.
- For example, after rotating
8000, we have0008which is considered as just8.
Given an integer n, return true if it is a confusing number, or false otherwise.
Example 1:

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

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

Input: n = 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
Constraints:
0 <= n <= 10^9
Solution
Approach: Rotate Digit by Digit
Rotating a number by 180 degrees does two things: each digit is flipped (0 -> 0, 1 -> 1, 6 -> 9, 8 -> 8, 9 -> 6) and the order of the digits is reversed, because the last digit ends up on top.
So peel the digits of n off from the right with % 10 and / 10. If a digit is one of 2, 3, 4, 5, 7, the rotation is invalid and the answer is false. Otherwise append its flipped digit to the rotated number (rotated = rotated * 10 + flipped): the digit we take first, the last one of n, becomes the first digit of the result. Leading zeros take care of themselves, since 8000 rotates to 0008, which is just the integer 8.
n is confusing when the rotation is valid and gives a different number. Note n = 0: it rotates to 0, so it is not confusing.
Complexity: O(d) time, where d is the number of digits of n, and O(1) extra space.
class Solution:
def confusingNumber(self, n: int) -> bool:
rotated_digit = [0, 1, -1, -1, -1, -1, 9, -1, 8, 6] # -1: the digit is invalid upside down
x, rotated = n, 0
while x > 0:
x, digit = divmod(x, 10)
if rotated_digit[digit] < 0:
return False
# The last digit of x becomes the first digit of the rotated number.
rotated = rotated * 10 + rotated_digit[digit]
return rotated != n