leetcode 869. Reordered Power of 2 | 869. 重新排序得到 2 的幂(状态压缩)

x33g5p2x  于2022-07-05 转载在 其他  
字(0.5k)|赞(0)|评价(0)|浏览(126)

题目

https://leetcode.com/problems/reordered-power-of-2/

题解

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拍平成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']++;
        }
        // 对array状态压缩
        // [0,0,1,0,0,1,2,0,0,0] -> 0010012000
        long res = 0;
        for (int c : count) {
            res *= 10;
            res += c;
        }
        return res;
    }
}

相关文章

微信公众号

最新文章

更多