Tech Master Tutorials
Email Facebook Google LinkedIn Pinterest Twitter
Home Java Java 8 Java Interview Questions Java Programming

Bits

All Possible Subsets:

	
//Bit manipulation can be used to find out all the subsets of a set. 
//If we have set of N elements then there are 2^N possible subsets of 
//the given set. So if we can represent each element in a subset with 
//a bit (either 0 or 1). This can be used to represent whether the 
//corresponding element belongs to this given subset or not.  Each bit 
//pattern will be a subset.
	
	
public class AllPossibleSubsets {

	public static void main(String[] args) {
		char[] arr={'A','B','C'};
		possibleSubsets(arr, arr.length);
	}
	
	static void possibleSubsets(char A[], int N)
	{
	    for(int i = 0;i < (1 << N); ++i)
	    {
	        for(int j = 0;j < N;++j)
	        {
	        	 
	            if((i & (1 << j))!=0)
	            {
	            	//Printing the selected elements for the particular subset
	                System.out.print(A[j]+" ");
	            }
	        }
	        System.out.println();
	    }
	}

}
	

Finding out if a number is a Power of 2::

public class PowerOfTwo {
	//Counting number of bits in a number

	public static void main(String[] args) {
		int num=4;
		System.out.println(isPowerOfTwo(num));
	}
	
	
	private static boolean isPowerOfTwo(int num) { 
		// if num==0 then function will return false 
		if(num==0){
			return false;
		}
		//if num is power of 2 then num&(num-1) will be zero 
		//because num will have only rightmost bit set as 1 and 
		//num-1 will have all other bits set as 1
		//so will return true
		//otherwise false
		return (num&(num-1))==0;
	}
	
	
}