[코테 풀이] Find the K-or of an Array

시내·2024년 6월 29일

Q_2917) Find the K-or of an Array

출처 : https://leetcode.com/problems/find-the-k-or-of-an-array/

class Solution {
    public int findKOr(int[] nums, int k) {
        int max = 0;
        ArrayList<String> arrayList = new ArrayList<>();
        ArrayList<String> arr = new ArrayList<>();
        for (int a : nums) {
            String toBin = Integer.toBinaryString(a);
            if (toBin.length() > max) max = toBin.length();
            arrayList.add(Integer.toBinaryString(a));
        }
        for (String n : arrayList) {
            if (n.length() < max) {
                int nn = n.length();
                for (int i = 0; i < max - nn; i++) {
                    n = "0" + n;
                }
            }
            arr.add(n);
        }
        int[] numOnes = countOnes(arr, max, k);
        int answer = 0;
        for (int q = 0; q < numOnes.length; q++) {
            answer += Math.pow(2, max-1) * numOnes[q];
            max--;
        }
        return answer;
    }
    
     public int[] countOnes(ArrayList<String> list, int max, int target) {
        int[] count = new int[max];
        int ind = 0;
        while (ind < max) {
            for (int i = 0; i < max; i++) {
                int counts = 0;
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j).charAt(i) == '1') counts++;
                }
                if (counts >= target) count[ind++] = 1;
                else count[ind++] = 0;
            }
        }
        return count;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글