File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed
src/main/java/com/ctci/bitmanipulation Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change @@ -28,7 +28,9 @@ private static String decimalFractionToBinaryString(double realNum) {
2828 return "ERROR" ;
2929 }
3030 realNum = realNum * 2 ;
31+ // the binary bit is the whole number part (left to the decimal)
3132 binaryBit = (int ) realNum ;
33+ // we only have to take the part after the decimal (right to the decimal) for the next iteration
3234 if (binaryBit == 1 ) {
3335 realNum -= 1 ;
3436 }
Original file line number Diff line number Diff line change 1+ package com .ctci .bitmanipulation ;
2+
3+ /**
4+ * @author rampatra
5+ * @since 2019-03-16
6+ */
7+ public class FlipBitToWin {
8+
9+ /**
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+ * longest sequence of 1s you could create.
12+ * Example:
13+ * Input: 1775 (or: 11011101111) Output: 8
14+ * <p>
15+ * Approach:
16+ * We just walk through the integer tracking the current 1s sequence length and the previous 1s sequence length.
17+ * When we see a zero, update previous length as follows:
18+ * - If the next bit is a 1, previous Length should be set to current Length.
19+ * - If the next bit is a 0, then we can't merge these sequences together. So, set previous Length to 0.
20+ *
21+ * @param n an integer
22+ * @return the longest sequence of set bits in {@code n} by flipping only one zero bit
23+ */
24+ private static int findLongestSequence (int n ) {
25+ // if all bits are set, return the total number of bits in an integer
26+ if (n == ~0 ) {
27+ return Integer .BYTES * 8 ;
28+ }
29+
30+ int prevOnesLen = 0 ;
31+ int currOnesLen = 0 ;
32+ int maxOnesLen = 0 ;
33+
34+ while (n > 0 ) {
35+ // if the current bit is 0, reset the currOnesLen
36+ if ((n & 1 ) == 0 ) {
37+ prevOnesLen = (n & 2 ) == 0 ? 0 : currOnesLen ; // if the next bit is also 0, set prevOnesLen to 0
38+ currOnesLen = 0 ;
39+ } else {
40+ currOnesLen ++;
41+ }
42+ n >>>= 1 ;
43+ maxOnesLen = Math .max (maxOnesLen , prevOnesLen + 1 + currOnesLen );
44+ }
45+ return maxOnesLen ;
46+ }
47+
48+ public static void main (String [] args ) {
49+ System .out .println ("Longest seq in " + Integer .toBinaryString (125 ) + " is " + findLongestSequence (125 ));
50+ System .out .println ("Longest seq in " + Integer .toBinaryString (1275 ) + " is " + findLongestSequence (1275 ));
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments