File tree Expand file tree Collapse file tree 2 files changed +54
-1
lines changed
src/main/java/com/ctci/bitmanipulation Expand file tree Collapse file tree 2 files changed +54
-1
lines changed Original file line number Diff line number Diff line change @@ -12,7 +12,7 @@ public class Conversion {
1212 * Example:
1313 * Input: 29 (or: 11101), 15 (or: 01111)
1414 * Output: 2
15- *
15+ *
1616 * @param a
1717 * @param b
1818 * @return the number of bits to flip
@@ -32,9 +32,32 @@ private static int countSetBits(int n) {
3232 return count ;
3333 }
3434
35+ /**
36+ * In this approach, we first take the xor of both the integers (which sets the bits at positions where the bits
37+ * in a and b are different). We then unset the least significant bit in each iteration (c & (c - 1)) and count the
38+ * number of iterations to find the bits to flip.
39+ *
40+ * @param a
41+ * @param b
42+ * @return the number of bits to flip
43+ */
44+ private static int getNoOfBitsToFlipToConvertAToBWithoutRightShift (int a , int b ) {
45+ int count = 0 ;
46+ for (int c = a ^ b ; c != 0 ; c = c & (c - 1 )) {
47+ count ++;
48+ }
49+ return count ;
50+ }
51+
3552 public static void main (String [] args ) {
3653 System .out .println (getNoOfBitsToFlipToConvertAToB (5 , 7 ));
3754 System .out .println (getNoOfBitsToFlipToConvertAToB (5 , 5 ));
3855 System .out .println (getNoOfBitsToFlipToConvertAToB (29 , 15 ));
56+
57+ System .out .println ("---" );
58+
59+ System .out .println (getNoOfBitsToFlipToConvertAToBWithoutRightShift (5 , 7 ));
60+ System .out .println (getNoOfBitsToFlipToConvertAToBWithoutRightShift (5 , 5 ));
61+ System .out .println (getNoOfBitsToFlipToConvertAToBWithoutRightShift (29 , 15 ));
3962 }
4063}
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 Debugger {
8+
9+ /**
10+ * If after un-setting the least significant bit in n, it becomes 0 then it implies that it has only set bit. This
11+ * can also imply that n is a power of 2.
12+ *
13+ * @param n input integer
14+ * @return {@code true} if n has only set bit, {@code false} otherwise.
15+ */
16+ private static boolean hasOneSetBit (int n ) {
17+ // edge case
18+ if (n == 0 ) {
19+ return false ;
20+ }
21+ return (n & (n - 1 )) == 0 ; // (n & (n - 1)) un-sets the least significant bit
22+ }
23+
24+ public static void main (String [] args ) {
25+ System .out .println (hasOneSetBit (0 ));
26+ System .out .println (hasOneSetBit (2 ));
27+ System .out .println (hasOneSetBit (16 ));
28+ System .out .println (hasOneSetBit (10 ));
29+ }
30+ }
You can’t perform that action at this time.
0 commit comments