diff --git a/src/TechInterview/BitManipulation1.java b/src/TechInterview/BitManipulation1.java new file mode 100644 index 0000000..6ab0873 --- /dev/null +++ b/src/TechInterview/BitManipulation1.java @@ -0,0 +1,34 @@ +import java.util.Scanner; +/** + * This class has solution to problem #5.1 'Insertion' + * of chapter 'BitManipulation' from book 'Cracking the Coding Interview'. + * @author akanksha bhardwaj + */ +public class BitManipulation1 { + + public void insertion(String N, String M, int i, int j) { + int n = Integer.parseInt(N,2); + int m = Integer.parseInt(M,2); + /* divide new number in three parts + * first part from number n ,all bits from the most significant bit through j+1 (inclusive) + * second part from number m complete + * third part from number n , all bits from i-1 through 0 (inclusive) + */ + int first = n & (-1 << (j+1)); + int second = m << i; + int third = n & ( (1 << i) - 1); + int num = (first | second ) | third ; + System.out.println(Integer.toBinaryString(num)); + } + public static void main(String[] args) { + + BitManipulation1 bm = new BitManipulation1(); + Scanner sc = new Scanner(System.in); + String N = sc.next(); + String M = sc.next(); + int i = sc.nextInt(); + int j = sc.nextInt(); + bm.insertion(N , M , i, j); + + } +} diff --git a/src/TechInterview/BitManipulation2.java b/src/TechInterview/BitManipulation2.java new file mode 100644 index 0000000..a40b022 --- /dev/null +++ b/src/TechInterview/BitManipulation2.java @@ -0,0 +1,41 @@ +import static java.lang.Integer.max; +import java.util.Scanner; +/** + * This class has solution to the problem #5.3 Flip Bit to Win + * of chapter 'BitManipulation' from book 'Cracking the Coding Interview'. + * @author akanksha bhardwaj + */ +public class BitManipulation2 { + + public void flipToWin(int n) { + String s = Integer.toBinaryString(n); + int l = s.length(); + char[] c = s.toCharArray(); + int prev_zindex = -1 ; // store index to previously encourtered 0 bit + int max_seq = 0 , curr_seq = 0; + for(int i = 0 ; i < l; i++) { + if(c[i] == '0') { + if(prev_zindex == -1) { // first 0 bit encountered + curr_seq = i + 1; + } + else { + max_seq = max(max_seq , curr_seq); // update answer with sequence value according to previous 0 bit + curr_seq = i - prev_zindex ; // update current sequence length according to this 0 bit + } + prev_zindex = i; + } + else { + curr_seq += 1; + } + } + max_seq = max(max_seq , curr_seq); + System.out.println(max_seq); + } + + public static void main(String[] args) { + BitManipulation2 bm = new BitManipulation2(); + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + bm.flipToWin(n); + } +}