|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * 788. Rotated Digits |
| 8 | + * |
| 9 | + * X is a good number if after rotating each digit individually by 180 degrees, |
| 10 | + * we get a valid number that is different from X. |
| 11 | + * A number is valid if each digit remains a digit after rotation. |
| 12 | + * 0, 1, and 8 rotate to themselves; |
| 13 | + * 2 and 5 rotate to each other; |
| 14 | + * 6 and 9 rotate to each other, |
| 15 | + * and the rest of the numbers do not rotate to any other number. |
| 16 | +
|
| 17 | + Now given a positive number N, how many numbers X from 1 to N are good? |
| 18 | +
|
| 19 | + Example: |
| 20 | + Input: 10 |
| 21 | + Output: 4 |
| 22 | +
|
| 23 | + Explanation: |
| 24 | + There are four good numbers in the range [1, 10] : 2, 5, 6, 9. |
| 25 | + Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. |
| 26 | +
|
| 27 | + Note: N will be in range [1, 10000]. |
| 28 | + */ |
| 29 | +public class _788 { |
| 30 | + public static class Solution1 { |
| 31 | + public int rotatedDigits(int N) { |
| 32 | + int count = 0; |
| 33 | + Map<Character, String> map = new HashMap<>(); |
| 34 | + map.put('0', "0"); |
| 35 | + map.put('1', "1"); |
| 36 | + map.put('8', "8"); |
| 37 | + map.put('2', "5"); |
| 38 | + map.put('5', "2"); |
| 39 | + map.put('6', "9"); |
| 40 | + map.put('9', "6"); |
| 41 | + for (int i = 1; i <= N; i++) { |
| 42 | + if (isRotatedNumber(i, map)) { |
| 43 | + count++; |
| 44 | + } |
| 45 | + } |
| 46 | + return count; |
| 47 | + } |
| 48 | + |
| 49 | + private boolean isRotatedNumber(int num, Map<Character, String> map) { |
| 50 | + String originalNum = String.valueOf(num); |
| 51 | + StringBuilder sb = new StringBuilder(); |
| 52 | + for (char c : String.valueOf(num).toCharArray()) { |
| 53 | + if (!map.containsKey(c)) { |
| 54 | + return false; |
| 55 | + } else { |
| 56 | + sb.append(map.get(c)); |
| 57 | + } |
| 58 | + } |
| 59 | + return !originalNum.equals(sb.toString()); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments