Confusing Number

Given a number N, return true if and only if it is a confusing number, which satisfies the following condition:

We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid. A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.

89 -> 68   Input: 89 Output: true Explanation: We get 68 after rotating 89, 86 is a valid number and 86!=89.

思路:逆序倒着加。注意int倒着,容易爆,转换成long

class Solution {
    public boolean confusingNumber(int N) {
        if(N < 0) {
            return false;
        }
        HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
        hashmap.put(0,0);
        hashmap.put(1,1);
        hashmap.put(6,9);
        hashmap.put(8,8);
        hashmap.put(9,6);
        long n = (long) N;
        return isconfused(hashmap, n);
    }
    
    private boolean isconfused(HashMap<Integer, Integer> hashmap, long n) {
        long res = 0;
        long x = n;
        while(x != 0) {
            int digit = (int) x % 10;
            if(digit == 2 || digit == 3 || digit == 4 || digit == 5 || digit == 7) {
                return false;
            }
            res = res*10 + hashmap.get(digit);
            x = x / 10;
        }
        return res != n;
    }
}
发布了663 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/105140284