Similar Problems
Similar Problems not available
Confusing Number - Leetcode Solution
Companies:
LeetCode: Confusing Number Leetcode Solution
Difficulty: Easy
Topics: math
The Confusing Number problem on LeetCode can be solved by first understanding what a confusing number is. A confusing number is a number whose digit rotation is different from the original number and it has at least one digit that is not one of 0, 1, 6, 8, or 9.
To solve this problem, we can iterate through the digits of the given number, checking each digit to see if it is one of 0, 1, 6, 8, or 9. If we find a digit that is not one of these values, then we know the number is a confusing number and we can return false.
Next, we need to perform the digit rotation of the number. We can create a hashmap to store the digit-to-rotation mappings. We can then iterate through the digits of the given number, replacing each digit with its rotation and storing the result in a new variable.
At the end of the iteration, we check if the new variable is different from the original number. If it is, we return true, indicating that the number is a confusing number. Otherwise, we return false.
Here is the implementation of the solution in Python:
class Solution:
def confusingNumber(self, n: int) -> bool:
rotate = {
"0": "0",
"1": "1",
"6": "9",
"8": "8",
"9": "6"
}
num_str = str(n)
rotated_num = ""
for digit in num_str:
if not digit in rotate:
return False
rotated_num += rotate[digit]
return rotated_num[::-1] != num_str
In this implementation, we first define a hashmap called rotate
which contains the digit-to-rotation mappings. We then convert the given number n
to a string and iterate through each of its digits. We check if each digit is one of 0, 1, 6, 8, or 9. If it is not, we return False immediately. If it is, we add its rotation to a new string called rotated_num
.
At the end of the iteration, we check if rotated_num
is different from the original number n
when reversed. If it is, we return True, indicating that the number is a confusing number. Otherwise, we return False.
Confusing Number Solution Code
1