Bit manipulation using Java with detailed explanation.


  • 0
    J

    Bit manipulation like the following example:
    0(000):{}
    1(001):{a}
    2(010):{b}
    3(011):{ab}
    4(100):{c}
    5(101):{a,c}
    6(110):{b,c}
    7(111):{a,b,c}

    class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List list = new LinkedList();
            int size = (int)Math.pow(2, nums.length) - 1;
            for(int i=0; i<=size; i++){
                String bits = Integer.toString(i,2);
                while(bits.length() != nums.length) bits = "0" + bits; //used to complement 0 if the numbers bits length not equal to nums length
                list.add(addToList(bits, nums));
            }
            return list;
        }
        
        //this function used to add each bit corresponding to 1 to list.
        private List addToList(String bits, int[] nums){
            List sub = new LinkedList<Integer>();
            for(int i=0; i<bits.length(); i++){
                if(bits.charAt(i) == '1') sub.add(nums[i]);
            }
            return sub;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.