Making a Binary Palindrome

You are given an array of integers, nums. In a single operation, you can either increment or decrement any element by 1. A "binary palindrome" is an integer whose base-2 representation (ignoring any leading zeros) reads the exact same forwards and backwards.

Your task is to return an array of the same length where each element represents the minimum number of operations required to convert the corresponding number in nums into a binary palindrome.

Example 1:

Input: nums = [11, 16, 23]

Output: [2, 1, 2]

Explanation: For the first element 11 (binary 1011), the closest binary palindrome is 9 (binary 1001), which requires 2 operations (decrements). For the second element 16 (binary 10000), we can either decrease it by 1 to reach 15 (1111) or increase it by 1 to reach 17 (10001); both optimally require exactly 1 operation. For the third element 23 (binary 10111), the nearest binary palindrome is 21 (binary 10101), costing exactly 2 operations.

Example 2:

Input: nums = [20, 32, 10]

Output: [1, 1, 1]

Explanation: The closest binary palindrome to 20 (10100) is 21 (10101), which requires a single increment operation. For 32 (100000), the closest palindromes are 31 (11111) and 33 (100001), both requiring exactly 1 operation. Finally, for 10 (1010), the closest binary palindrome is 9 (1001), which also requires just 1 operation to achieve.

Now Your Turn!

Pick the correct output for the given input

Input : nums = [9, 18, 32]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= nums.length <= 5000
  • ​​​​​​​1 <= nums[i] <= 5000

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
vector<int> minOperations(vector<int>& nums) {
// Write your code here
return {};
}
};
Test Case

Input:

Nums