3750. Minimum Number of Flips to Reverse Binary String
Description
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.
Example 1:
Input: n = 7
Output: 0
Explanation:
The binary representation of 7 is "111". Its reverse is also "111", which is the same. Hence, no flips are needed.
Example 2:
Input: n = 10
Output: 4
Explanation:
The binary representation of 10 is "1010". Its reverse is "0101". All four bits must be flipped to make them equal. Thus, the minimum number of flips required is 4.
Constraints:
1 <= n <= 109
Solutions
Solution 1: Simulation
We first convert the integer \(n\) into a binary string \(s\). Then we use two pointers to traverse from both ends of the string towards the center, counting the number of positions where the characters differ, denoted as \(cnt\). Since each flip can only affect one bit, the total number of flips is \(cnt \times 2\).
The time complexity is \(O(\log n)\) and the space complexity is \(O(\log n)\), where \(n\) is the input integer.
1 2 3 4 5 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |