[LeetCode] Minimum Operations to Make Binary Palindrome

3766. Minimum Operations to Make Binary Palindrome

You are given an integer array nums.

For each element nums[i], you may perform the following operations any number of times (including zero):

  • Increase nums[i] by 1, or
  • Decrease nums[i] by 1.

A number is called a binary palindrome if its binary representation without leading zeros reads the same forward and backward.

Your task is to return an integer array ans, where ans[i] represents the minimum number of operations required to convert nums[i] into a binary palindrome.

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
class Solution {
bool bit(int n, int x) {
return (n>>x) & 1;
}
bool ok(int x) {
int l = 64ll - __builtin_clzll(x) - 1ll, r = 0;
while(r < l) {
if(bit(x,l) != bit(x,r)) return false;
l--,r++;
}
return true;
}
public:
vector<int> minOperations(vector<int>& nums) {
int ma = *max_element(begin(nums), end(nums)) * 2;
vector<int> A;
for(int i = 1; i <= ma; i++) if(ok(i)) A.push_back(i);
for(auto& n : nums) {
int ri = lower_bound(begin(A), end(A), n) - begin(A), le = ri - 1;
if(le == -1) n = A[ri] - n;
else n = min(A[ri] - n, n - A[le]);
}
return nums;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-operations-to-make-binary-palindrome/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.