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 - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored); 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.
A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored); 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.
Now given a positive number
N
, how many numbers X from 1
to N
are good?Example:
Input: n = 10
Output: 4
Approach
Java
public class RotatedDigits {public static void main(String[] args) {int n = 10;System.out.println(rotatedDigits(n));}static int rotatedDigits(int N) {int cnt = 0;for (int i = 1; i <= N; i++) {int j = i;StringBuffer str = new StringBuffer();int flag = 0;while (j > 0) {if (j % 10 == 3 || j % 10 == 4 || j % 10 == 7) {flag = 1;break;} else if (j % 10 == 2)str = str.append(5);else if (j % 10 == 5)str = str.append(2);else if (j % 10 == 6)str = str.append(9);else if (j % 10 == 9)str = str.append(6);elsestr = str.append(j % 10);j = j / 10;}str = str.reverse();if (flag == 0 && !str.toString().equals(String.valueOf(i)))cnt++;}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;int rotatedDigits(int N){int cnt = 0;for (int i = 1; i <= N; i++){int j = i;string str = "";int flag = 0;while (j > 0){if (j % 10 == 3 || j % 10 == 4 || j % 10 == 7){flag = 1;break;}else if (j % 10 == 2)str += "5";else if (j % 10 == 5)str += "2";else if (j % 10 == 6)str += "9";else if (j % 10 == 9)str += "6";elsestr += to_string(j % 10);j = j / 10;}reverse(str.begin(), str.end());if (flag == 0 && str != to_string(i))cnt++;}return cnt;}int main(){int n = 10;cout << rotatedDigits(n);return 0;}
No comments:
Post a Comment