Given a positive integer n, what is the mathematical effect of evaluating n 1?
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Given a positive integer n, what is the mathematical effect of evaluating n >> 1?
Show answer & explanation
The right shift operator >> shifts all bits one position to the right, which is equivalent to dividing by 2 and discarding any remainder (floor division). For positive integers, n >> 1 = floor(n / 2). Options B, C, and D are incorrect: multiplication by 2 is left shift, modulo 2 extracts the least significant bit, and sign inversion is the bitwise NOT operator.
Step-by-step Derivation:
Binary representation example:
n = 13 (binary: 1101)
n >> 1 shifts bits right: 0110 (binary) = 6 (decimal)
13 / 2 = 6.5, floor(6.5) = 6 ✓
n = 20 (binary: 10100)
n >> 1 shifts bits right: 01010 (binary) = 10 (decimal)
20 / 2 = 10 ✓
Mathematically: n >> 1 = ⌊n / 2⌋