1279. Find Absolute Value Without Branching

EasyBit ManipulationBit ManipulationSign BitBranchless

Given a 32-bit signed integer n, return its absolute value without using any conditional branch (no if statements or comparisons). Use the sign bit to build the result with bitwise operations.

Input: A JSON object {"n": <integer>} within 32-bit signed range.

Output: Return the absolute value of n as an integer.

Examples

Example 1
Input: {"n":-9}
Output: 9
Explanation: Sign mask is all ones; (n+mask)^mask = 9.
Example 2
Input: {"n":9}
Output: 9
Explanation: Sign mask is 0, so the value is unchanged -> 9.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →