[LeetCode] Minimum Number of Flips to Reverse Binary String

3750. Minimum Number of Flips to Reverse Binary String

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int minimumFlips(int n) {
string bin = bitset<64>(n).to_string().substr(bitset<64>(n).to_string().find('1'));
int res = 0, l = 0, r = bin.size() - 1;
while(l < r) {
if(bin[l] != bin[r]) res++;
l++,r--;
}
return res<<1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/11/23/PS/LeetCode/minimum-number-of-flips-to-reverse-binary-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.