Compute the integer absolute value (abs) without branching
Last Updated : 28 Mar, 2024
We need not to do anything if a number is positive. We want to change only negative numbers. Since negative numbers are stored in 2's complement form, to get the absolute value of a negative number we have to toggle bits of the number and add 1 to the result.
For example -2 in a 8 bit system is stored as follows 1 1 1 1 1 1 1 0 where leftmost bit is the sign bit. To get the absolute value of a negative number, we have to toggle all bits and add 1 to the toggled number i.e, 0 0 0 0 0 0 0 1 + 1 will give the absolute value of 1 1 1 1 1 1 1 0. Also remember, we need to do these operations only if the number is negative (sign bit is set).
Method 1
1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n>>31
2) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number.
mask + n
3) XOR of mask +n and mask gives the absolute value.
(mask + n)^mask
Implementation:
C++ #include <bits/stdc++.h> using namespace std; #define CHARBIT 8 /* This function will return absolute value of n*/ unsigned int getAbs(int n) { int const mask = n >> (sizeof(int) * CHARBIT - 1); return ((n + mask) ^ mask); } /* Driver program to test above function */ int main() { int n = -6; cout << "Absolute value of " << n << " is " << getAbs(n); return 0; } // This code is contributed by rathbhupendra
C #include <stdio.h> #define CHAR_BIT 8 /* This function will return absolute value of n*/ unsigned int getAbs(int n) { int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver program to test above function */ int main() { int n = -6; printf("Absolute value of %d is %u", n, getAbs(n)); getchar(); return 0; }
Java // Java implementation of above approach import java.io.*; class GFG { static final int CHAR_BIT = 8; static final int SIZE_INT = 8; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ public static void main(String[] args) { int n = -6; System.out.print("Absolute value of " + n + " is " + getAbs(n)); } } // This code is contributed by Rajput-Ji
Python # Python3 implementation of above approach CHARBIT = 8; SIZE_INT = 8; # This function will return # absolute value of n def getAbs(n): mask = n >> (SIZE_INT * CHARBIT - 1); return ((n + mask) ^ mask); # Driver Code n = -6; print("Absolute value of",n,"is",getAbs(n)); # This code is contributed by mits
C# // C# implementation of above approach using System; class GFG { static int CHAR_BIT = 8; static int SIZE_INT = 4; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ static void Main() { int n = -6; Console.Write("Absolute value of " + n + " is " + getAbs(n)); } } // This code is contributed by mits
JavaScript // javascript implementation of above approach var CHAR_BIT = 8; var SIZE_INT = 8; /* This function will return absolute value of n */ function getAbs(n) { var mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ var n = -6; console.log("Absolute value of " + n + " is " + getAbs(n)); // This code is contributed by shikhasingrajput
PHP <?php // PHP implementation of above approach $CHARBIT = 8; $SIZE_INT = 8; // This function will return // absolute value of n function getAbs($n) { global $SIZE_INT, $CHARBIT; $mask = $n >> ($SIZE_INT * $CHARBIT - 1); return (($n + $mask) ^ $mask); } // Driver Code $n = -6; echo "Absolute value of " . $n . " is " . getAbs($n); // This code is contributed by mits ?>
OutputAbsolute value of -6 is 6
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 2:
1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n>>31
2) XOR the mask with number
mask ^ n
3) Subtract mask from result of step 2 and return the result.
(mask^n) - mask
Implementation:
C++ #include <bits/stdc++.h> using namespace std; /* This function will return absolute value of n*/ unsigned int getAbs(int n) { int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n ^ mask) - mask); } /* Driver program to test above function */ int main() { int n = -6; cout << "Absolute value of " << n << " is " << getAbs(n); return 0; } // This code is contributed by phalasi.
C #include <stdio.h> #include <limits.h> //to include CHAR_BIT /* This function will return absolute value of n*/ unsigned int getAbs(int n) { int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n ^ mask) - mask); } /* Driver program to test above function */ int main() { int n = -6; printf("Absolute value of %d is %d\n", n, getAbs(n)); return 0; }
Java // Java implementation of above approach import java.io.*; class GFG { static final int CHAR_BIT = 8; static final int SIZE_INT = 8; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n ^ mask) - mask); } /* Driver code */ public static void main(String[] args) { int n = -6; System.out.print("Absolute value of " + n + " is " + getAbs(n)); } } // This code is contributed by code_hunt.
Python import os import sys # This function will return absolute value of n def getAbs(n): mask = n >> (sys.getsizeof(int()) * os.sysconf('SC_CHAR_BIT') - 1) return ((n ^ mask) - mask) # Driver code n = -6 print("The absolute value of", n, "is", getAbs(n)) # This code is contributed by phalasi.
C# // C# implementation of above approach using System; public class GFG { static int CHAR_BIT = 8; static int SIZE_INT = 4; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } } // This code is contributed by Rajput-Ji
JavaScript // JavaScript code to implement the approach /* This function will return absolute value of n*/ function getAbs(n) { // note: the size of int is 256 bytes // and the size of char is 8 bytes const mask = n >> (256 * 8 - 1); return ((n ^ mask) - mask); } /* Driver program to test above function */ var n = -6; console.log("Absolute value of %d is %d", n, getAbs(n)); // this code is contributed by phasing17.
OutputAbsolute value of -6 is 6
Time Complexity: O(1)
Auxiliary Space: O(1)
On machines where branching is expensive, the above expression can be faster than the obvious approach, r = (v < 0) ? -(unsigned)v : v, even though the number of operations is the same.
Please see this for more details about the above two methods.
Please write comments if you find any of the above explanations/algorithms incorrect, or a better ways to solve the same problem.
References:
http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
Similar Reads
Compute the minimum or maximum of two integers without branching On some rare machines where branching is expensive, the below obvious approach to find minimum can be slow as it uses branching. C++ /* The obvious approach to find minimum (involves branching) */ int min(int x, int y) { return (x < y) ? x : y } //This code is contributed by Shubham Singh Java /*
11 min read
Find a pair with sum N having minimum absolute difference Given an integer N, the task is to find a distinct pair of X and Y such that X + Y = N and abs(X - Y) is minimum. Examples: Input: N = 11Output: 5 6 Explanation:X = 5 and Y = 6 satisfy the given equation. Therefore, the minimum absolute value of abs(X - Y) = 1. Input: N = 12 Output: 5 7 Naive Approa
6 min read
Maximum absolute difference between any two level sum in a Binary Tree Given a Binary Tree having positive and negative nodes, the task is to find the maximum absolute difference of level sum in it. Examples: Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 9 Explanation: Sum of all nodes of 0 level is 4 Sum of all nodes of 1 level is -3 Sum of all nodes of 2 level is 6 Hen
10 min read
Computing INT_MAX and INT_MIN with Bitwise operations Prerequisites : INT_MAX and INT_MIN in C/C++ and Applications. Arithmetic shift vs Logical shiftSuppose you have a 32-bit system : The INT_MAX would be 01111111111111111111111111111111 and INT_MIN would be 10000000000000000000000000000000. 0 & 1 in most-significant bit position representing the
4 min read
Find Maximum and Minimum of two numbers using Absolute function Given two numbers, the task is to print the maximum and minimum of the given numbers using Absolute function.Examples: Input: 99, 18 Output: Maximum = 99 Minimum = 18 Input: -10, 20 Output: Maximum = 20 Minimum = -10 Input: -1, -5 Output: Maximum = -1 Minimum = -5 Approach: This problem can be solve
5 min read
Minimize sum of absolute values of A[i] - (B + i) for a given array Given an array arr[ ] of size N, the task is to find the minimum possible value of the expression abs(arr[1] - (b + 1)) + abs(arr[2] - (b + 2)) . . . abs(arr[N] - (b + N)), where b is an independent integer. Input: arr[ ] = { 2, 2, 3, 5, 5 }Output: 2Explanation: Considering b = 0: The value of the e
5 min read