File tree 2 files changed +42
-1
lines changed
src/main/java/com/ctci/bitmanipulation
2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -10,7 +10,8 @@ public class FlipBitToWin {
10
10
* 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
11
11
* longest sequence of 1s you could create.
12
12
* Example:
13
- * Input: 1775 (or: 11011101111) Output: 8
13
+ * Input: 1775 (or: 11011101111)
14
+ * Output: 8
14
15
* <p>
15
16
* Approach:
16
17
* We just walk through the integer tracking the current 1s sequence length and the previous 1s sequence length.
You can’t perform that action at this time.
0 commit comments