Related Articles
Compute maximum of two integers in C/C++ using Bitwise Operators
• Difficulty Level : Medium
• Last Updated : 05 Nov, 2020

Given two integers A and B, the task is to find the maximum of two numbers using Bitwise Operators.

Examples:

Input: A = 40, B = 54
Output: 54

Input: A = -1, B = -10
Output: -1

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use the Bitwise Operator as well as the Right Shift Operator to find the greatest number between two distinct numbers without using any conditional statements( if … ) and Ternary Operator(?: ). Below are the steps:

• Find the maximum value on the basis of the below expression:

z = A – B
i = (z >> 31) & 1
max = a – (i*z)

• Subtract two numbers and store it in another variable z.
• To get the sign of the number obtained after subtraction, apply Right Shift to the variable z and store it in another variable i and then perform Bitwise AND operation on the variable i with 1 to get values in 1 or 0.
• Perform the following expression to get the largest value among the two given numbers as max = (a – (i * z)).

Illustration:

A = 40, B = 54
z = (A – B) = 40 – 54 = -14
i = -1 & 1 = 1
max = a – (i * z) = (40 – (1 * -14)) = 54

Below is the implementation of the above approach:

## C

 `// C program for the above approach ` `#include ` ` `  `// Function to find the largest number ` `int` `findMax(``int` `a, ``int` `b) ` `{ ` `    ``int` `z, i, max; ` ` `  `    ``// Perform the subtraction ` `    ``z = a - b; ` ` `  `    ``// Right shift and Bitwise AND ` `    ``i = (z >> 31) & 1; ` ` `  `    ``// Find the maximum number ` `    ``max = a - (i * z); ` ` `  `    ``// Return the maximum value ` `    ``return` `max; ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``int` `A = 40, B = 54; ` ` `  `    ``// Function Call ` `    ``printf``(``"%d"``, findMax(A, B)); ` ` `  `    ``return` `0; ` `} `

## C++

 `// C++ program for above approach ` `#include ` `using` `namespace` `std; ` ` `  `// Function to find the largest number ` `int` `findMax(``int` `a, ``int` `b) ` `{ ` `    ``int` `z, i, max; ` ` `  `    ``// Perform the subtraction ` `    ``z = a - b; ` ` `  `    ``// Right shift and Bitwise AND ` `    ``i = (z >> 31) & 1; ` ` `  `    ``// Find the maximum number ` `    ``max = a - (i * z); ` ` `  `    ``// Return the maximum value ` `    ``return` `max; ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``int` `A = 40, B = 54; ` ` `  `    ``// Function Call ` `    ``cout << findMax(A, B); ` ` `  `    ``return` `0; ` `} `

Output:

```54
```

Time Complexity: O(1)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :