Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package g3701_3800.s3750_minimum_number_of_flips_to_reverse_binary_string;

// #Easy #String #Math #Two_Pointers #Bit_Manipulation #Mid_Level #Biweekly_Contest_170
// #2026_04_26_Time_1_ms_(100.00%)_Space_42.88_MB_(49.74%)

public class Solution {
public int minimumFlips(int n) {
int ans = 0;
int temp = n;
int l = 0;
int r = -1;
while (temp > 0) {
temp >>= 1;
r++;
}
while (l < r) {
ans += ((n >> l) & 1) ^ ((n >> r) & 1);
l++;
r--;
}
return 2 * ans;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
3750\. Minimum Number of Flips to Reverse Binary String

Easy

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:**

* <code>1 <= n <= 10<sup>9</sup></code>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package g3701_3800.s3750_minimum_number_of_flips_to_reverse_binary_string;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class SolutionTest {
@Test
void minimumFlips() {
assertThat(new Solution().minimumFlips(7), equalTo(0));
}

@Test
void minimumFlips2() {
assertThat(new Solution().minimumFlips(10), equalTo(4));
}
}
Loading