X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated, and the result must be a valid number.
Each digit must be rotated as follows:
A number is valid if each digit can be rotated to form another valid digit. A number is different if it does not include any of {3, 4, 7}.
Given a positive integer N
, how many numbers X from 1 to N are good?
N
is 0 or 1? We should handle small values of N
correctly.N
(1 <= N <= 10^4). We need to ensure the solution scales well within this range.1
to N
.def rotatedDigits(N: int) -> int:
def is_good(number):
valid = {'0', '1', '8', '2', '5', '6', '9'}
changes = {'2', '5', '6', '9'}
num_str = str(number)
if any(digit in '347' for digit in num_str):
return False
return any(digit in changes for digit in num_str)
count = 0
for num in range(1, N + 1):
if is_good(num):
count += 1
return count
# Example usage:
print(rotatedDigits(10)) # Output: 4
is_good
):
number
converted to string form allows easy iteration digit by digit.rotatedDigits
):
1
to N
.is_good
to check each number.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?