Day 6: Bitwise Operators (10 Days of Javascript)

Task:

We define S to be a sequence of distinct sequential integers from 1 to n; in other words,s={1,2,3,…,n} . We want to know the maximum bitwise AND value of any two integers, a and b (where a<b), in sequence S that is also less than a given integer,K .

Complete the function in the editor so that given n and K, it returns the maximum a&b<k.

Note: The & symbol represents the bitwise AND operator.


Solution:


function getMaxLessThanK(n, k) {
    let maxNum = 0;

    for (let i=1;i<=n;i++) {
        for (let j=i+1;j<= n;j++) {
            let exp =i&j;

            if(exp < k && exp > maxNum)
              maxNum=exp;
        }
    }
 
    return maxNum;
}

Leave a Reply