Home > database >  Return an array containing all indices that are powers of 2
Return an array containing all indices that are powers of 2

Time:10-12

I'm working on this problem. Math is not one of strong suites. Any tips would be great. It is supposed to return an array of indices that are powers of 2.

function secondPower(arr) {
    // Return an array containing all indices that are powers of 2
    newArray = [];

    for(let i = 0; i < arr.length; i  ){
        if(arr[i] % (2 ** i) === 0  && arr[i] != 1){
            newArray.push(arr[i]);
        }
    }
    return newArray;
}

An example of the solution is

secondPower([1, 2, 3, 4, 5, 6, 7, 8]) 

returns

[2,3,5]

CodePudding user response:

You can use bitwise operators, that are LOTS FASTER. But they only works for power of 2:

function secondPower(arr) {
    var result = [];
    for (var k = 0; k < arr.length; k  ) {
        if (isPower(k)) { result.push(arr[k]); }
    }
    return result;
}

//... this function checks if there is only one 1 on the binary number
function isPower(k) {
    var found = false;
    while (k > 0) {
        if (k & 1 == 1) {
            if (found) { return false; }
            found = true;
        }
        k >>= 1;
    }
    return found;
}

secondPower([1, 2, 3, 4, 5, 6, 7, 8]);
  • Related