Skip to content

Commit a682b9f

Browse files
authored
Added task 3750
1 parent 787946c commit a682b9f

3 files changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g3701_3800.s3750_minimum_number_of_flips_to_reverse_binary_string;
2+
3+
// #Easy #String #Math #Two_Pointers #Bit_Manipulation #Mid_Level #Biweekly_Contest_170
4+
// #2026_04_26_Time_1_ms_(100.00%)_Space_42.88_MB_(49.74%)
5+
6+
public class Solution {
7+
public int minimumFlips(int n) {
8+
int ans = 0;
9+
int temp = n;
10+
int l = 0;
11+
int r = -1;
12+
while (temp > 0) {
13+
temp >>= 1;
14+
r++;
15+
}
16+
while (l < r) {
17+
ans += ((n >> l) & 1) ^ ((n >> r) & 1);
18+
l++;
19+
r--;
20+
}
21+
return 2 * ans;
22+
}
23+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
3750\. Minimum Number of Flips to Reverse Binary String
2+
3+
Easy
4+
5+
You are given a **positive** integer `n`.
6+
7+
Let `s` be the **binary representation** of `n` without leading zeros.
8+
9+
The **reverse** of a binary string `s` is obtained by writing the characters of `s` in the opposite order.
10+
11+
You may flip any bit in `s` (change `0 → 1` or `1 → 0`). Each flip affects **exactly** one bit.
12+
13+
Return the **minimum** number of flips required to make `s` equal to the reverse of its original form.
14+
15+
**Example 1:**
16+
17+
**Input:** n = 7
18+
19+
**Output:** 0
20+
21+
**Explanation:**
22+
23+
The binary representation of 7 is `"111"`. Its reverse is also `"111"`, which is the same. Hence, no flips are needed.
24+
25+
**Example 2:**
26+
27+
**Input:** n = 10
28+
29+
**Output:** 4
30+
31+
**Explanation:**
32+
33+
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.
34+
35+
**Constraints:**
36+
37+
* <code>1 <= n <= 10<sup>9</sup></code>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package g3701_3800.s3750_minimum_number_of_flips_to_reverse_binary_string;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void minimumFlips() {
11+
assertThat(new Solution().minimumFlips(7), equalTo(0));
12+
}
13+
14+
@Test
15+
void minimumFlips2() {
16+
assertThat(new Solution().minimumFlips(10), equalTo(4));
17+
}
18+
}

0 commit comments

Comments
 (0)