当前位置:网站首页>leetcode 869. Reordered Power of 2 | 869. Reorder to a power of 2 (state compression)

leetcode 869. Reordered Power of 2 | 869. Reorder to a power of 2 (state compression)

2022-07-08 02:03:00 Cold spring HQ

subject

https://leetcode.com/problems/reordered-power-of-2/
 Insert picture description here

Answer key

class Solution {
    
    public boolean reorderedPowerOf2(int n) {
    
        Set<Long> set = new HashSet<>();
        int target = 1;
        for (int i = 0; i < 31; i++) {
    
            set.add(compress(target));
            target <<= 1;
        }
        return set.contains(compress(n));
    }

    public long compress(int n) {
    
        // int Pai Pingcheng array
        // index 0 1 2 3 4 5 6 7 8 9
        // num=2566 -> [0,0,1,0,0,1,2,0,0,0]
        int[] count = new int[10];
        for (char c : String.valueOf(n).toCharArray()) {
    
            count[c - '0']++;
        }
        //  Yes array State compression 
        // [0,0,1,0,0,1,2,0,0,0] -> 0010012000
        long res = 0;
        for (int c : count) {
    
            res *= 10;
            res += c;
        }
        return res;
    }
}

 Insert picture description here

原网站

版权声明
本文为[Cold spring HQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/189/202207080037095771.html