JavaScript Bit Manipulation with Explaination


  • 0

    0_1474676423622_78. Subsets.jpg

    /**
     * @param {number[]} nums
     * @return {number[][]}
     */
    var subsets = function(nums) {
        if (nums.length === 0)
            return [];
            
        var len = nums.length,
            count = Math.pow(2, len),
            result = [];
            
        for (var i = 0; i < count; i++) {
            // to binary string
            var str = i.toString(2);
            
            // get one subset from binary string
            var subset = [];
            // iterate the string from back to front since our binary string is
            // e.g.: "11" instead of "011" when i = 3 
            for (var k = str.length - 1; k >= 0; k--) {
                if (str[k] == '1')
                    subset.unshift(nums[len - str.length  + k]);
            }
            
            result.push(subset);
        }
        
        return result;
    };
    

  • 0

    @dukewan
    a great way!

    And I changed it like this..

    var subsets = function(nums) {
        if (nums.length === 0)
            return [];
            
        var len = nums.length,
            count = Math.pow(2, len),
            result = [];
            
        for (var i = 0; i < count; i++) {
            // to binary string
            var str = i.toString(2);
            
            // get one subset from binary string
            var subset = [];
    
           //===============
            var prefix = len - str.length;
    
            for (var k = 0, l = str.length; k < l; k++) {
              if (str[k] === '1') {
                subset.push(nums[k + prefix]);
              }
            }
            //==============
            result.push(subset);
        }    
        return result;
    };
    

    the length of every str must has the same value with len in this program. so that I set prefix to fix it.


Log in to reply
 

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