The answer is guaranteed to fit in a 32-bit signed integer.
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).
Total of operations: 1 + 2 + 2 = 5.
Input: nums = [2,2]
Output: 3
Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
Double all the elements: [1, 1] -> [2, 2] (1 operation).
Total of operations: 2 + 1 = 3.
Input: nums = [4,2,5]
Output: 6
Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).
Input: nums = [3,2,2,4]
Output: 7
Input: nums = [2,4,8,16]
Output: 8
class Solution {
public int minOperations(int[] nums) {
int count = 0;
// N*Log(Range)
while (true) {
boolean allZeros = true;
for (int i = 0; i < nums.length; i++) {
count += nums[i] % 2;
nums[i] /= 2;
if (nums[i] != 0)
allZeros = false;
}
if (allZeros)
break;
else
// Count for diving the array by 2
count++;
}
return count;
}
}