Created
November 20, 2018 17:10
-
-
Save redatawfik/9bc1056976611412cd062bbe6dd94648 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package CTCI; | |
import java.util.Scanner; | |
public class BitManipulation { | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
int x1 = scan.nextInt(), i = scan.nextInt(); | |
System.out.println(Integer.toBinaryString(x1)); | |
System.out.println(Integer.toBinaryString(modifyBit(x1, i, 1))); | |
//System.out.println(differentBits(x1, x2)); | |
} | |
static int setBit(int x, int position) { | |
int mask = 1 << position; | |
return x | mask; | |
} | |
static int clearBit(int x, int position) { | |
int mask = 1 << position; | |
return x & ~mask; | |
} | |
static int flipBit(int x, int position) { | |
int mask = 1 << position; | |
return x ^ mask; | |
} | |
static boolean isBitSet(int x, int position) { | |
int mask = 1 << position; | |
int res = x & mask; | |
return res != 0; | |
} | |
static int modifyBit(int x, int position, int state) { | |
int mask = ~(1 << position); | |
return (x & mask) | (state << position); | |
} | |
static boolean isEven(int x) { | |
int res = x & 1; | |
return res == 0; | |
} | |
static boolean isPowerOfTwo(int x) { | |
int res = x & x - 1; | |
return res == 0; | |
} | |
static int differentBits(int a, int b) { | |
int x = a ^ b; | |
int count = 0; | |
while (x != 0) { | |
if (isBitSet(x, 0)) count++; | |
x = x >> 1; | |
} | |
return count; | |
} | |
static int clearBitsMSBthroughI(int num, int i) { | |
int mask = (-1 << (i + 1)); | |
return num & mask; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment