forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1558.java
73 lines (68 loc) · 2.13 KB
/
_1558.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.fishercoder.solutions;
public class _1558 {
public static class Solution1 {
public int minOperations(int[] nums) {
int ops = 0;
while (!allZero(nums)) {
if (allEvenAndNonZeroes(nums)) {
nums = half(nums);
ops++;
} else if (hasOdds(nums)) {
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 != 0) {
result[i] = nums[i] - 1;
ops++;
} else {
result[i] = nums[i];
}
}
nums = result;
} else {
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
result[i] = nums[i] / 2;
} else {
result[i] = nums[i];
}
}
nums = result;
ops++;
}
}
return ops;
}
private boolean hasOdds(int[] nums) {
for (int i : nums) {
if (i % 2 != 0) {
return true;
}
}
return false;
}
private int[] half(int[] nums) {
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
result[i] = nums[i] / 2;
}
return result;
}
private boolean allEvenAndNonZeroes(int[] nums) {
for (int i : nums) {
if (i % 2 != 0 || i == 0) {
return false;
}
}
return true;
}
private boolean allZero(int[] nums) {
for (int i : nums) {
if (i != 0) {
return false;
}
}
return true;
}
}
}