divideByTwo

Easy · Bit Manipulation · 3 test cases

Divide an integer by 2 and truncate the result (integer division) using only bitwise operators.

Examples

divideByTwo(10) → 5
divideByTwo(7) → 3
divideByTwo(-5) → -3

Starter code

function divideByTwo(n) {

}

Complexity of the optimal solution

Time O(1), space O(1). The sign-propagating right shift `>>` operator shifts all bits to the right, effectively dividing by a power of 2 and truncating toward negative infinity. A shift by 1 divides by 2. This is a constant time CPU instruction.

Solve divideByTwo in the browser