#3766
Medium Algorithms Minimum operations to make binary palindrome
Array Two Pointers Binary Search Bit Manipulation
51.6% acceptance
Feb 25, 2026
51
10
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.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn min_operations(nums: Vec<i32>) -> Vec<i32> {
fn is_bin_palindrome(n: i32) -> bool {
let bits: Vec<u8> = format!("{:b}", n).bytes().collect();
let len = bits.len();
(0..len / 2).all(|i| bits[i] == bits[len - 1 - i])
}
nums.iter().map(|&n| {
if is_bin_palindrome(n) { return 0; }
let mut d = 1i32;
loop {
if n - d >= 1 && is_bin_palindrome(n - d) { return d; }
if is_bin_palindrome(n + d) { return d; }
d += 1;
}
}).collect()
}
}