gpt4 book ai didi

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

转载 作者:知者 更新时间:2024-03-13 04:26:03 25 4
gpt4 key购买 nike

题目

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com