788. Rotated Digits

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; 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 numberN, how many numbers X from1toNare good?

Example:
Input:
 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.

Note:

  • N will be in range [1, 10000] .
class Solution {
    public int rotatedDigits(int N) {
        Map<Character, Character> hash = new HashMap<>();
        hash.put('0', '0');
        hash.put('1', '1');
        hash.put('2', '5');
        hash.put('5', '2');
        hash.put('6', '9');
        hash.put('9', '6');
        hash.put('8', '8');

        int ans = 0;
        for (int i = 1; i <= N; i++){

            int temp = convert(i, hash);
            if (temp != -1 && temp != i){
                //System.out.println("found: " + temp);
                ans++;  
            } 
        }

        return ans;
    }

    private int convert(int num, Map<Character, Character> hash){
        String numStr = String.valueOf(num);

        char[] cArray = numStr.toCharArray();
        for (int i = 0; i < cArray.length; i++){
            if (!hash.containsKey(cArray[i])) return -1;

            cArray[i] = hash.get(cArray[i]);
        }

        numStr = new String(cArray);

        return Integer.parseInt(numStr);
    }
}

results for ""

    No results matching ""