Confusing Number

Understanding the Problem

A number is considered confusing if after rotating its digits by 180 degrees, we get a valid number that is different from the original number.

Steps to Solve

  1. Create a Mapping: First, we need to create a mapping for valid rotations. This mapping will contain which digit can be converted to which digit after rotation.
  2. Rotate the Number: We will read the digits of the number from right to left and apply the rotation according to our mapping. If we find an invalid digit that cannot be rotated, we return False.
  3. Compare with the Original: Finally, we will compare the rotated number with the original number. If they are the same, return False. If they are different, return True.

Code Implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def confusingNumber(self, n: int) -> bool:
        # Step 1: Create a mapping for valid rotations
        mapping = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}

        # Step 2: Rotate the number
        rotated_number = 0
        original_number = n
        while n > 0:
            digit = n % 10
            if digit not in mapping: # Invalid digit found
                return False
            rotated_number = rotated_number * 10 + mapping[digit]
            n //= 10

        # Step 3: Compare with the original
        return rotated_number != original_number

Examples

  • For n = 6, the rotated number is 9, so the result is True.
  • For n = 89, the rotated number is 68, so the result is True.
  • For n = 11, the rotated number is 11, so the result is False.

Complexity

The time complexity of this solution is O(log n), where n is the input number, and the space complexity is O(1) as we are using a constant amount of extra space.