[코테 풀이] Sum of Values at Indices With K Set Bits

시내·2024년 6월 12일
0

Q_2859) Sum of Values at Indices With K Set Bits

출처 : https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits/

class Solution {
    public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        int sum = 0;
        int chk = 0;

        for (int i = 0; i < nums.size(); i++) {
            int count = 0;
            String toBinary = Integer.toBinaryString(i);
            for (int b = 0; b < toBinary.length(); b++) {
                if (toBinary.charAt(b) == '1') {
                    count++;
                }
            }
            if (count == k) {
                arrayList.add(chk);
            }
            chk++;
        }

        for (int a : arrayList) {
            sum += nums.get(a);
        }
        return sum;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글