当前位置:网站首页>leetcode 869. Reordered Power of 2 | 869. 重新排序得到 2 的幂(状态压缩)

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

2022-07-08 00:37:00 寒泉Hq

题目

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;
    }
}

在这里插入图片描述

原网站

版权声明
本文为[寒泉Hq]所创,转载请带上原文链接,感谢
https://hanquan.blog.csdn.net/article/details/125609631