Skip to content

Commit eef7cb0

Browse files
committedJul 5, 2024
solve #2859: Sum of Values at Indices With K Set Bits in java
1 parent 9423033 commit eef7cb0

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed
 

Diff for: ‎README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -855,7 +855,7 @@
855855
| 2843 | [Count Symmetric Integers](https://leetcode.com/problems/count-symmetric-integers) | [![Java](assets/java.png)](src/CountSymmetricIntegers.java) | |
856856
| 2848 | [Points That Intersect With Cars](https://leetcode.com/problems/points-that-intersect-with-cars) | [![Java](assets/java.png)](src/PointsThatIntersectWithCars.java) | |
857857
| 2855 | [Minimum Right Shifts to Sort the Array](https://leetcode.com/problems/minimum-right-shifts-to-sort-the-array) | [![Java](assets/java.png)](src/MinimumRightShiftsToSortTheArray.java) | |
858-
| 2859 | [Sum of Values at Indices With K Set Bits](https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits) | | |
858+
| 2859 | [Sum of Values at Indices With K Set Bits](https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits) | [![Java](assets/java.png)](src/SumOfValuesAtIndicesWithKSetBits.java) | |
859859
| 2833 | [Furthest Point From Origin](https://leetcode.com/problems/furthest-point-from-origin) | | |
860860
| 2839 | [Check if Strings Can be Made Equal With Operations I](https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i) | | |
861861
| 2843 | [Count Symmetric Integers](https://leetcode.com/problems/count-symmetric-integers) | | |

Diff for: ‎src/SumOfValuesAtIndicesWithKSetBits.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits
2+
// T: O(N)
3+
// S: O(1)
4+
5+
import java.util.List;
6+
7+
public class SumOfValuesAtIndicesWithKSetBits {
8+
public int sumIndicesWithKSetBits(List<Integer> array, int k) {
9+
int sum = 0;
10+
for (int i = 0 ; i < array.size() ; i++) {
11+
if (numberOfSetBits(i) == k) {
12+
sum += array.get(i);
13+
}
14+
}
15+
return sum;
16+
}
17+
18+
private static int numberOfSetBits(int number) {
19+
int setBits = 0;
20+
while (number > 0) {
21+
setBits += number % 2;
22+
number /= 2;
23+
}
24+
return setBits;
25+
}
26+
}

0 commit comments

Comments
 (0)