Optimised Approach
In this approach, the function calculates the bitwise OR of numbers in the range from ‘start’ to ‘end’. It first computes the bitwise OR of numbers from 1 to ‘start – 1’ and from 1 to ‘end’, then combines them to find the result.
Example: Implementation to compute the bitwise OR of all numbers in a range with an optimised solution.
function ORN(n) {
if (n % 2 === 0) return n - 1;
return n;
}
function ORRange(start, endValue) {
const startMinusOne = ORN(start - 1);
const end = ORN(endValue);
return startMinusOne | end;
}
const startValue = 3;
const endValue = 7;
const result = ORRange(startValue, endValue);
console.log(result);
Output
7
Time Complexity: O(1)
Space Complexity: O(1)
JavaScript Program to Compute the Bitwise OR of all Numbers in a Range
In JavaScript, bitwise operations provide a way to manipulate individual bits of numeric values. The bitwise OR operation (|) combines the bits of two operands, resulting in a new value where each bit is set if it is set in either operand.