Description
An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. For example:
0,1, and8rotate to themselves,2and5rotate to each other (in this case they are rotated in a different direction, in other words,2or5gets mirrored),6and9rotate to each other, and- the rest of the numbers do not rotate to any other number and become invalid.
Given an integer n, return the number of good integers in the range [1, n].
Example 1:
Input: n = 10 Output: 4 Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9. Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
Example 2:
Input: n = 1 Output: 0
Example 3:
Input: n = 2 Output: 1
Constraints:
1 <= n <= 104
Solutions
This function counts how many numbers from 1 to n are "good rotated digits" — numbers that look like valid numbers when their digits are rotated 180 degrees. It uses a cache to remember previous results for optimization. For each number, it checks every digit: digits 0, 1, 8 stay the same when rotated, digits 2, 5, 6, 9 transform into different valid digits (making the number "rotated"), and digits 3, 4, 7 don't form valid digits when rotated. The function increments a counter only for numbers that contain exclusively valid digits AND have at least one transforming digit (2, 5, 6, or 9), then it stores the final result in the cache and returns the count.
const cache = [[0, 0]];
/**
* @param {number} n
* @return {number}
*/
var rotatedDigits = function(n) {
let start = 1;
let count = 0;
for (const [s, c] of cache) {
if (s + 1 <= n && s + 1 > start) {
start = s + 1;
count = c;
}
}
for (let x = start; x <= n; x++) {
let num = x;
let rotated = false;
while (num > 0) {
const rem = num % 10;
if (rem === 2 || rem === 5 || rem === 6 || rem === 9) rotated = true;
if (rem === 3 || rem === 4 || rem === 7) break;
num = ~~(num / 10);
}
if (num === 0 && rotated) {
count++;
}
}
cache.push([n, count]);
return count;
};