Skip to content

Commit 33d903c

Browse files
committed
Flip bits done
1 parent 39ea032 commit 33d903c

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.ctci.bitmanipulation;
2+
3+
/**
4+
* @author rampatra
5+
* @since 2019-03-17
6+
*/
7+
public class Conversion {
8+
9+
/**
10+
* Write a function to determine the number of bits you would need to flip to convert
11+
* integer A to integer B.
12+
* Example:
13+
* Input: 29 (or: 11101), 15 (or: 01111)
14+
* Output: 2
15+
*
16+
* @param a
17+
* @param b
18+
* @return the number of bits to flip
19+
*/
20+
private static int getNoOfBitsToFlipToConvertAToB(int a, int b) {
21+
return countSetBits(a ^ b);
22+
}
23+
24+
private static int countSetBits(int n) {
25+
int count = 0;
26+
while (n > 0) {
27+
if ((n & 1) == 1) {
28+
count++;
29+
}
30+
n >>>= 1;
31+
}
32+
return count;
33+
}
34+
35+
public static void main(String[] args) {
36+
System.out.println(getNoOfBitsToFlipToConvertAToB(5, 7));
37+
System.out.println(getNoOfBitsToFlipToConvertAToB(5, 5));
38+
System.out.println(getNoOfBitsToFlipToConvertAToB(29, 15));
39+
}
40+
}

src/main/java/com/ctci/bitmanipulation/FlipBitToWin.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ public class FlipBitToWin {
1010
* You have an integer and you can flip exactly one bit from a O to a 1. Write code to find the length of the
1111
* longest sequence of 1s you could create.
1212
* Example:
13-
* Input: 1775 (or: 11011101111) Output: 8
13+
* Input: 1775 (or: 11011101111)
14+
* Output: 8
1415
* <p>
1516
* Approach:
1617
* We just walk through the integer tracking the current 1s sequence length and the previous 1s sequence length.

0 commit comments

Comments
 (0)