forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
40 lines (40 loc) · 958 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public int minOperations(List<Integer> nums, int target) {
long s = 0;
int[] cnt = new int[32];
for (int x : nums) {
s += x;
for (int i = 0; i < 32; ++i) {
if ((x >> i & 1) == 1) {
++cnt[i];
}
}
}
if (s < target) {
return -1;
}
int i = 0, j = 0;
int ans = 0;
while (true) {
while (i < 32 && (target >> i & 1) == 0) {
++i;
}
if (i == 32) {
return ans;
}
while (j < i) {
cnt[j + 1] += cnt[j] / 2;
cnt[j] %= 2;
++j;
}
while (cnt[j] == 0) {
cnt[j] = 1;
++j;
}
ans += j - i;
--cnt[j];
j = i;
++i;
}
}
}