788. Rotated Digits
X is a good number if after rotating each digit individually by 180 degrees, we get a valid digit and the result is different from X. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit becomes another digit after rotation, where the digits are:
However, the digits 3, 4, and 7 are not valid after rotation.
Given an integer N
, return the number of good numbers in the range [1, N].
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 rotation.
isGoodNumber
to check the validity of each number.isGoodNumber
to count how many are good.public class RotatedDigits {
public int rotatedDigits(int N) {
int count = 0;
for (int i = 1; i <= N; i++) {
if (isGoodNumber(i)) {
count++;
}
}
return count;
}
private boolean isGoodNumber(int n) {
boolean isValid = false;
while (n > 0) {
int d = n % 10;
if (d == 3 || d == 4 || d == 7) {
return false;
}
if (d == 2 || d == 5 || d == 6 || d == 9) {
isValid = true;
}
n /= 10;
}
return isValid;
}
public static void main(String[] args) {
RotatedDigits solution = new RotatedDigits();
System.out.println(solution.rotatedDigits(10)); // Output: 4
}
}
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?