Check if The Number is Fascinating

The code is a solution to check if the number n is fascinating or not.

Understanding the Code

  1. Define a Helper Function: The helper function pan takes a string num as input. It checks if the sorted list of characters in num is exactly ["1","2","3","4","5","6","7","8","9"]. If it is, the function returns True, indicating that num contains all the digits from 1 to 9 exactly once. Otherwise, it returns False.

  2. Concatenate the Numbers: Outside the helper function, n is concatenated with 2 * n and 3 * n to form a single string.

  3. Check for Fascinating Number: Finally, the concatenated string is passed to the pan function, and its result is returned.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def isFascinating(self, n: int) -> bool:
        # Helper function to check if a number is pan-digital (contains all digits from 1 to 9 exactly once)
        def pan(num):
            if sorted(list(num)) == ["1","2","3","4","5","6","7","8","9"]:
                return True
            else:
                return False

        # Concatenate n, 2 * n, and 3 * n
        n = str(n) + str(n * 2) + str(n * 3)

        # Check if the concatenated number is fascinating using the helper function
        return pan(n)

Key Takeaways

  • The code makes use of a helper function to perform the specific check for the fascinating number condition.
  • It employs string concatenation and sorting to determine whether the concatenated number meets the required conditions.