#3750
Easy Algorithms Minimum number of flips to reverse binary string
Math Two Pointers String Bit Manipulation
75.8% acceptance
Feb 25, 2026
35
0
You are given a positive integer n.
Let s be the binary representation of n without leading zeros.
The reverse of a binary string s is obtained by writing the characters of s in the opposite order.
You may flip any bit in s (change 0 → 1 or 1 → 0). Each flip affects exactly one bit.
Return the minimum number of flips required to make s equal to the reverse of its original form.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_flips(n: i32) -> i32 {
let bits: Vec<u8> = format!("{:b}", n).bytes().map(|b| b - b'0').collect();
let len = bits.len();
(0..len).filter(|&i| bits[i] != bits[len - 1 - i]).count() as i32
}
}