무냐의 개발일지
2859. Sum of Values at Indices With K Set Bits 본문
👩💻 문제
You are given a 0-indexed integer array nums and an integer k.
Return an integer that denotes the sum of elements in nums whose corresponding indices have exactly k set bits in their binary representation.
The set bits in an integer are the 1's present when it is written in binary.
For example, the binary representation of 21 is 10101, which has 3 set bits.
Example 1:
Input: nums = [5,10,1,5,2], k = 1
Output: 13
Explanation: The binary representation of the indices are:
0 = 0002
1 = 0012
2 = 0102
3 = 0112
4 = 1002
Indices 1, 2, and 4 have k = 1 set bits in their binary representation.
Hence, the answer is nums[1] + nums[2] + nums[4] = 13.
💡 풀이
class Solution:
def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
res =[]
for i in range(len(nums)):
if bin(i)[2:].count('1') == k:
res.append(nums[i])
return sum(res)
✍️ 해설
그.. 리스트의 인덱스를 2진법으로 표현했을 때, 그 숫자가 k개만큼의 1을 가진 숫자들에 해당되는 자리에 있는
숫자끼리 더해서 return하는 문제이다!! 문제가 좀 살짝 꼬여있다.
1. 인덱스를 2진법으로 표현
2. 그 중 1이 k개 있는 인덱스만 추출
3. 그 인덱스 자리에 있는 리스트의 숫자들을 sum , return
🥳 배운점
bin 처리하면 binary 이진수로 바뀌고, 0b100 이런 식으로 앞에 이진법임을 나타내는 0b가 붙기 때문에, 이걸 제거해주기 위해 [2:] 를 추가로 써준다.
int 처리하면 10진수로 바뀐다. ==> int(binary값, 2) 하면 2진수인 숫자를 10진법으로 처리한다는 뜻. 이런 식으로 다른 진법의 수도 10진법으로 처리 가능하다 !
count 함수를 잘 활용하여, 인덱스에 1이 몇 개 있는지 쉽게 셀 수 있었다.
'LeetCode 코딩테스트' 카테고리의 다른 글
1791. Find Center of Star GraphS (0) | 2024.05.09 |
---|---|
1920. Build Array from Permutation (0) | 2024.04.15 |
2114. Maximum Number of Words Found in Sentences (0) | 2024.04.13 |
1281. Subtract the Product and Sum of Digits of an Integer (0) | 2024.04.13 |
938. Range Sum of BST (0) | 2024.04.13 |