这些方法对于获得小于n的2的最大功率是否有效?

时间:2017-07-04 11:02:31

标签: javascript

以下所有有效的方法是否能找到比值本身小的最大幂?

function largestPowOf2Smaller1(n) {
    if (n === 0 || n === 1) {
        throw 'too small';
    }
    n = n-1;
    let pow = 0;
    while (n > 0) {
        n >>= 1;
        pow++;
    }
    return pow-1;
}

function largestPowOf2Smaller2(n) {
    if (n === 0 || n === 1) {
        throw 'too small';
    }
    return (n-1).toString(2).length-1;
}

function largestPowOf2Smaller3(n) {
    if (n === 0 || n === 1) {
        throw 'too small';
    }
    return Math.floor(Math.log2(n-1));
}

// "Tests"
console.log(largestPowOf2Smaller1(2)); // 0
console.log(largestPowOf2Smaller2(2)); // 0
console.log(largestPowOf2Smaller3(2)); // 0

console.log(largestPowOf2Smaller1(4)); // 1
console.log(largestPowOf2Smaller2(4)); // 1
console.log(largestPowOf2Smaller3(4)); // 1

console.log(largestPowOf2Smaller1(8)); // 2
console.log(largestPowOf2Smaller2(8)); // 2
console.log(largestPowOf2Smaller3(8)); // 2

console.log(largestPowOf2Smaller1(9)); // 3
console.log(largestPowOf2Smaller2(9)); // 3
console.log(largestPowOf2Smaller3(9)); // 3

0 个答案:

没有答案