A clear explanation of checking if a number becomes a different valid number when rotated 180 degrees.
Problem Restatement
A confusing number is a number that when rotated 180 degrees becomes a different valid number.
The valid rotations are: 0 → 0, 1 → 1, 6 → 9, 8 → 8, 9 → 6.
Digits 2, 3, 4, 5, 7 are invalid — rotating them produces no valid digit.
We are given a number n. Return true if it is a confusing number.
Input and Output
| Item | Meaning |
|---|---|
| Input | Integer n |
| Output | true if rotating 180° gives a different valid number |
Function shape:
def confusingNumber(n: int) -> bool:
...Examples
Example 1:
n = 6Rotating 6 gives 9. Valid and different. Answer: True.
Example 2:
n = 89Rotating gives 68. Valid and different. Answer: True.
Example 3:
n = 11Rotating 11 gives 11. Same number. Answer: False.
Key Insight
Build the rotated number by reversing the digits and applying the rotation map. If any digit is invalid, return False. If the rotated number differs from the original, return True.
Edge Cases
- Check the minimum input size allowed by the constraints.
- Verify duplicate values or tie cases if the input can contain them.
- Keep the return value aligned with the exact failure case in the statement.
Common Pitfalls
- Do not optimize away the invariant; the code should still make it clear what condition is being maintained.
- Prefer problem-specific names over one-letter variables once the logic becomes stateful.
Implementation
class Solution:
def confusingNumber(self, n: int) -> bool:
rotate = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
original = n
rotated = 0
while n > 0:
digit = n % 10
if digit not in rotate:
return False
rotated = rotated * 10 + rotate[digit]
n //= 10
return rotated != originalTesting
def run_tests():
s = Solution()
assert s.confusingNumber(6) == True
assert s.confusingNumber(89) == True
assert s.confusingNumber(11) == False
assert s.confusingNumber(25) == False
print("all tests passed")
run_tests()| Test | Expected | Why |
|---|---|---|
6 | True | Rotates to 9 |
89 | True | Rotates to 68 |
11 | False | Rotates to 11 (same) |
25 | False | 2 is not a valid rotation digit |