Skip to content

Commit e6cac3d

Browse files
Bit Manipulation: 2220. Minimum Bit Flips to Convert Number
1 parent 33d6e99 commit e6cac3d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package bit_manipulation.easy;
2+
3+
/***
4+
* Problem 2220 in Leetcode: https://leetcode.com/problems/minimum-bit-flips-to-convert-number/
5+
*
6+
* A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0.
7+
* For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it.
8+
* We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc.
9+
* Given two integers start and goal, return the minimum number of bit flips to convert start to goal.
10+
*
11+
* Example 1:
12+
* Input: start = 10, goal = 7
13+
* Output: 3
14+
*
15+
* Example 2:
16+
* Input: start = 3, goal = 4
17+
* Output: 3
18+
*/
19+
20+
public class MinimumBitFlipsToConvertNumber {
21+
public static void main(String[] args) {
22+
int start = 3, goal = 4;
23+
24+
System.out.println("Minimum bits: " + minimumBitsFlipsToConvertNumber(start, goal));
25+
}
26+
27+
private static int minimumBitsFlipsToConvertNumber(int start, int goal) {
28+
int xor = start ^ goal;
29+
int count = 0;
30+
31+
while (xor != 0) {
32+
if ((xor & 1) == 1) {
33+
count++;
34+
}
35+
xor >>= 1;
36+
}
37+
38+
return count;
39+
}
40+
}

0 commit comments

Comments
 (0)